0

I am trying to create a manual legend when plotting two time series as two columns of one dataset on a figure.

ggplot(data,aes(x=datetime)) + geom_line( aes(y=y1), color = 'red') + geom_line(aes( y=y2),color='blue')  

I am getting a figure with no legend so far enter image description here

I just need to add a legend with names for the colors red and blue like:

enter image description here

Faraz
  • 67
  • 7
  • 1
    This gets asked a lot on Stack Overflow, and there are many examples on here if you use the search bar at the top, but I have closed this as a duplicate, since the first answer in the linked duplicate question should give you a working solution. Essentially, you need to add `color = "Y1"` inside the `aes` call in the first geom_line,, and `color = "Y2"` inside the `aes` of the second one. Remove the `color = "red"` and `color = "blue"` from outside the `aes` calls. Then specify the colors by adding `+ scale_color_manual(values = c("red", "blue"))` to your plot. – Allan Cameron Nov 02 '22 at 18:58
  • 1
    Although the best way to do it would be to pivot uour data into long format, since then you only need a single `geom_line` layer. The linked duplicate shows how that is done too. – Allan Cameron Nov 02 '22 at 18:59

0 Answers0