改变ggplot中的线条颜色

时间:2018-03-16 14:32:07

标签: r ggplot2

我有这个数据框:

dftt <- data.frame(values = runif(11*4,0,1),
                 col = c(rep(2,4),
                         rep(1,4),
                         rep(5,9*4)),
                 x= rep(1:4, 11*4),
                 group=rep(factor(1:11), each=4)
                 )

> head(dftt)
     values col x group
1 0.2576930   2 1     1
2 0.4436522   2 2     1
3 0.5258673   2 3     1
4 0.2751512   2 4     1
5 0.5941050   1 1     2
6 0.7596024   1 2     2

我这样画:

ggplot(dftt, aes(x=x, y=values, group=group, color=col)) + geom_line() 

enter image description here

如何更改线条颜色,我希望前两条线为黑色和红色(在上图中它们都是黑色),其余线条为灰色(它们是浅蓝色)?

2 个答案:

答案 0 :(得分:1)

您是否有理由尝试通过col添加颜色?在我看来,这很奇怪,因为col的值比组少。如果您只想为组着色,这将是正确的方法:

  ggplot(dftt, aes(x=x, y=values, group=group, color=group)) + 
  geom_line() +
  scale_color_manual(values = c("black",
                                "red",
                                rep("gray", 9)))

enter image description here

答案 1 :(得分:1)

将您的col列转换为某个因子,然后将scale_color_manual添加到您的绘图功能中。

library(ggplot2)
dftt$col<-as.factor(dftt$col)

ggplot(dftt, aes(x=x, y=values, group=group, color=col)) + geom_line(size=1.2) +
  scale_color_manual(values=c( "black", "red", "blue"))

您可能需要重新排列色标以匹配您选择的颜色(1,2和5)

相关问题