Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

r - 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 using 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...