Add legend to geom_line() graph in r
As has been said, a color must be specified inside an aesthetic in order for there to be a legend. However, the color inside the aesthetic is actually just a label that then carries through to other layers. Setting custom colors can be done with scale_color_manual
and the legend label can be fixed with labs
.
ggplot(data=Summary)+
geom_line(mapping=aes(y=Y1,x= X,color="Y1"),size=1 ) +
geom_line(mapping=aes(y=Y2,x= X,color="Y2"),size=1) +
scale_color_manual(values = c(
'Y1' = 'darkblue',
'Y2' = 'red')) +
labs(color = 'Y series')
ggplot
needs aes
to make a legend, moving colour
inside aes(...)
will build a legend automatically. then we can adjust the labels-colors pairing via scale_color_manual
:
ggplot()+
geom_line(data=Summary,aes(y=Y1,x= X,colour="Y1"),size=1 )+
geom_line(data=Summary,aes(y=Y2,x= X,colour="Y2"),size=1) +
scale_color_manual(name = "Y series", values = c("Y1" = "darkblue", "Y2" = "red"))
To provide a more compact answer which only uses a single geom
call:
ggplot2
really likes long data (key-value pairs) better than wide (many columns). This requires you to transform your data prior to plotting it using a package like tidyr
or reshape2
. This way you can have a variable denoting color, inside your aes
call, which will produce the legend.
For your data:
library(tidyr)
library(ggplot2)
plot_data <- gather(data, variable, value, -x)
ggplot(plot_data, aes(x = x, y = value, color = variable)) +
geom_line() +
scale_color_manual(values = c("firebrick", "dodgerblue"))
You can then customize the legend via scale_color
series of helpers.