【问题标题】:Vary the color gradient on a scatter plot created with ggplot2改变使用 ggplot2 创建的散点图上的颜色渐变
【发布时间】:2011-04-21 08:14:03
【问题描述】:

是否可以通过美学来改变情节的颜色渐变?我正在使用类似于下面显示的行的代码生成一个图,并发现在某些情况下,区分各个组并不总是那么容易。例如,在下面的图表中,如果我可以让 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)

【问题讨论】:

  • 我不认为你能做到这一点,至少不容易。它只是没有映射到底层逻辑。
  • 加上传说会很混乱

标签: r ggplot2


【解决方案1】:

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

【讨论】:

  • 工作得很好,谢谢。我花了一点时间才意识到,grp 列需要是一个因素,然后数据框需要按这些因素进行排序。
猜你喜欢
  • 2023-03-21
  • 2017-01-14
  • 2017-07-19
  • 2012-02-12
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 2012-12-05
  • 2019-10-21
相关资源
最近更新 更多