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

时间:2011-04-20 21:38:38

标签: r ggplot2

是否可以通过审美来改变绘图的颜色渐变?我正在使用与下面给出的线类似的代码生成一个图,并且在某些情况下发现并不总是很容易区分不同的组。例如,在下面的图表中,如果我可以让A组点使用白蓝渐变而B组点使用白红渐变,则更容易区分结果。

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 个答案:

答案 0 :(得分:6)

你可以在调用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)