开发者

Vary the color gradient on a scatter plot created with ggplot2

Is it possible to vary a plot's color gradient by aesthetic? I'm generating a plot us开发者_如何学Pythoning code similar the lines presented below and finding in some cases that it is not always easy to distinguish between the various groups. For example, on the chart below it would be easier to distinguish the results if I could have the group A points use a white-blue gradient and the group B points use a white-red gradient.

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)


you can do that by preparing color by yourself before calling ggplot2.
Here is an example:

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜