1

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.

DaveRGP
  • 1,430
  • 15
  • 34
  • 2
    You want to move colour outside of `aes` like this: `geom_line(aes(y = ValueA), colour = "green")`. Then, you will see the four colors. – jazzurro Jan 20 '15 at 11:24
  • @jazzurro, solved. If you put it in an answer I'll accept it :) Knew it had to be simple. – DaveRGP Jan 20 '15 at 11:26
  • 1
    @DaveRGP Please take your time to read an introductory text about `ggplot`. The difference about _setting_ and _mapping_ aesthetics is central. See e.g. the first two examples [**here**](http://www.cookbook-r.com/Graphs/Colors_%28ggplot2%29/). – Henrik Jan 20 '15 at 11:31

1 Answers1

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")

enter image description here

jazzurro
  • 23,179
  • 35
  • 66
  • 76