How can I use different color palettes for different layers in ggplot2?

試著忘記壹切 提交于 2019-12-18 06:12:25

问题


Is it possible to plot two sets of data on the same plot, but use different color palettes for each set?

testdf <- data.frame( x = rnorm(100), 
                  y1 = rnorm(100, mean = 0, sd = 1), 
                  y2 = rnorm(100, mean = 10, sd = 1),
                  yc = rnorm(100, mean = 0, sd = 3))
ggplot(testdf, aes(x, y1, colour = yc)) + geom_point() +
  geom_point(aes(y = y2))

What I would like to see is one set of data, say y1, in blues (color set by yc), and the other set in reds (again color set by yc).

The legend should then show 2 color scales, one in blue, the other red.

Thanks for your suggestions.


回答1:


If you translate the "blues" and "reds" to varying transparency, then it is not against ggplot's philosophy. So, using Thierry's Moltenversion of the data set:

ggplot(Molten, aes(x, value, colour = variable, alpha = yc)) + geom_point()

Should do the trick.




回答2:


That's not possible with ggplot2. I think it against the philosophy of ggplot2 because it complicates the interpreatation of the plot.

Another option is to use different shapes to separate the points.

testdf <- data.frame( x = rnorm(100), 
                      y1 = rnorm(100, mean = 0, sd = 1), 
                      y2 = rnorm(100, mean = 10, sd = 1),
                      yc = rnorm(100, mean = 0, sd = 3))
Molten <- melt(testdf, id.vars = c("x", "yc"))
ggplot(Molten, aes(x, value, colour = yc, shape = variable)) + geom_point()


来源:https://stackoverflow.com/questions/9427950/how-can-i-use-different-color-palettes-for-different-layers-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!