R – change line color in ggplot

ggplot2r

I have this data frame:

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

I plot it like this:

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

enter image description here

How can I change the line colors, I want the first two lines to be black and red (in the above plot they are both black) and the remaining lines to be gray (they are light blue)?

Best Answer

Is there a reason why you even try adding colors via col? It seems to me like this is strange as col has fewer values than group. If you just want to color the groups, this would be the correct way:

  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

Related Topic