r - 具有 ggplot2 较低级别图的多种颜色缩放

标签 r colors ggplot2 aesthetics

每次我向主图中添加另一个 geom_line() 时,我希望实现不同的颜色渐变,每次都以“颜色”作为比例。 这是一个数据框作为示例:

df <- data.frame("letter"=c(rep("a",5),rep("b",5)),"x"=rep(seq(1,5),2),"y1"=c(seq(6,10),seq(6,10)/2),"y2"=c(seq(1,5),seq(1,5)/2),"y3"=c(seq(3,7),seq(3,7)/2))

我首先绘制:

y1 <- ggplot(df,aes(x=x,y=y1,colour=letter))+geom_line()
y1

然后我想添加 y1 和 y2,我可以这样做:

y2 <- geom_line(data=df,aes(x=x,y=y2,colour=letter))
y3 <- geom_line(data=df,aes(x=x,y=y3,colour=letter))
y1+y2+y3

但我希望 y1、y2 和 y3 的颜色渐变(或色调)不同!

是否可以将诸如scale_colour_hue()之类的东西分配给每个geom_line,或者这仅适用于ggplot?

谢谢!

最佳答案

正如我上面概述的,这里有一些选项:

df <- data.frame("letter"=c(rep("a",5),rep("b",5)),
                 "x"=rep(seq(1,5),2),
                 "y1"=c(seq(6,10),seq(6,10)/2),
                 "y2"=c(seq(1,5),seq(1,5)/2),
                 "y3"=c(seq(3,7),seq(3,7)/2))

# melt your data and create a grouping variable
library(plyr)                    
df_m <- melt(df,id.vars = 1:2)
df_m$grp <- with(df_m,interaction(letter,variable))


# Option 1
ggplot(df_m,aes(x = x, y = value)) + 
    facet_wrap(~variable) + 
    geom_line(aes(group = letter,colour = letter))

enter image description here

# Option 2      
ggplot(df_m,aes(x = x, y = value)) + 
    geom_line(aes(group = grp,colour = letter,linetype = variable))

enter image description here

关于r - 具有 ggplot2 较低级别图的多种颜色缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11192984/

相关文章:

r - 一次分离多个包裹

r - 如何选择具有特定值的光栅像素?

r markdown vitae 包 "Undefined control sequence"编织到 vitae 预定义简历模板时出错

android - 如何更改未聚焦的 textInputLayout 的轮廓或边框的颜色?

r Shiny : highlight some cells

R : How to config ggplotly displaying values on the line graph?

html - 桌面边框不会变色

algorithm - 什么是获得颜色以使图像上的文本突出的好算法?

r - ggTimeSeries 手动连续颜色

r - 如何使用不同的数据帧在 ggplot 中创建线型图例