Setting colour of a line in a ggplot2 expression w

2019-05-30 09:13发布

问题:

I would like to plot a different line for each of my series in this data set:

example <- data.frame(xAxis = c(1, 2, 3, 4, 5),
                  ValueA = c(5.5, 4.5, 4, 2.9, 2),
                  ValueB = c(5, 5.3, 5, 4.7, 4),
                  ValueC = c(4, 3.2, 3, 4, 3),
                  ValueD = c(5, 4.5, 3, 2.9, 3))

Following what seems like the intended usage of geom_line and aes in the ggplot2 package, I construct my graph like so:

library(ggplot2)

ggplot(example, aes(x = xAxis)) + 
    geom_line(aes(y = ValueA)) + 
    geom_line(aes(y = ValueB)) + 
    geom_line(aes(y = ValueC)) + 
    geom_line(aes(y = ValueD))

Setting the colour argument though is creating problems. Using the following seems to label the series, but not affect the colour selection:

ggplot(example, aes(x = xAxis)) + 
geom_line(aes(y = ValueA, colour = "green")) + 
geom_line(aes(y = ValueB, colour = "blue")) + 
geom_line(aes(y = ValueC, colour = "yellow")) + 
geom_line(aes(y = ValueD, colour = "red"))

However, if I set each of them to "red", then the plot understands to set them all to "red".

ggplot(example, aes(x = xAxis)) + 
geom_line(aes(y = ValueA, colour = "red")) + 
geom_line(aes(y = ValueB, colour = "red")) + 
geom_line(aes(y = ValueC, colour = "red")) + 
geom_line(aes(y = ValueD, colour = "red"))

What have I missed? I've seen that a 'standard' answer to multiple series plots in ggplot is to also use reshape to melt the data, but I feel there should be a decent solution here without needing that.

回答1:

The solution is to move the colour argument outside of aes(). Then, you will see the four colours you specified.

ggplot(example, aes(x = xAxis)) + 
geom_line(aes(y = ValueA), colour = "green") + 
geom_line(aes(y = ValueB), colour = "blue") + 
geom_line(aes(y = ValueC), colour = "yellow") + 
geom_line(aes(y = ValueD), colour = "red")



标签: r plot ggplot2