改变使用ggplot2创建的散点图上的颜色渐变

问题描述:

是否可以通过审美来改变绘图的颜色渐变?我使用类似于下面提供的代码的代码生成一个阴谋,并在某些情况下发现,区分各个群体并不总是很容易。例如,在下面的图表中,如果我可以让A组点使用白蓝色渐变,而B组点使用白红色渐变,则更容易区分结果。改变使用ggplot2创建的散点图上的颜色渐变

data <- data.frame(x=c(1,2,3,4,5,6,1,2,3,4,5,6), 
    y=c(1,2,3,4,5,6,1,2,3,4,5,6), grp=c(rep("A",6),rep("B",6)), 
    dt=c("2010-06-30","2010-05-31","2010-04-30", 
     "2010-03-31","2010-02-26","2010-01-29","2010-06-30", 
     "2010-05-31","2010-04-30", 
     "2010-03-31","2010-02-26","2010-01-29")) 
p <- ggplot(data, aes(x,y,color=as.integer(as.Date(data$dt)))) + 
    geom_jitter(size=4, alpha=0.75, aes(shape=grp)) + 
    scale_colour_gradient(limits=as.integer(as.Date(c("2010-01-29","2010-06-30"))), 
    low="white", high="blue") + 
    scale_shape_discrete(name="") + 
    opts(legend.position="none") 
print(p) 
+1

我不认为你能做到这一点,至少不容易。它只是没有映射到底层逻辑上。 – Ista 2011-04-20 22:43:02

+0

再加上一个传说会让人感到困惑 – hadley 2011-04-21 03:15:50

你可以在调用ggplot2之前自己准备颜色来做到这一点。
下面是一个例子:

data$sdt <- rescale(as.numeric(as.Date(data$dt))) # data scaled [0, 1] 
cols <- c("red", "blue") # colour of gradients for each group 

# here the color for each value are calculated 
data$col <- ddply(data, .(grp), function(x) 
    data.frame(col=apply(colorRamp(c("white", cols[as.numeric(x$grp)[1]]))(x$sdt), 
     1,function(x)rgb(x[1],x[2],x[3], max=255))) 
     )$col 

p <- ggplot(data, aes(x,y, shape=grp, colour=col)) + 
    geom_jitter(size=4, alpha=0.75) + 
    scale_colour_identity() + # use identity colour scale 
    scale_shape_discrete(name="") + 
    opts(legend.position="none") 
print(p) 
+1

工作很好,谢谢。我花了一些时间才意识到grp列需要成为一个因素,然后数据框需要按这些因素排序。 – user338714 2011-04-21 06:14:04