I\'ve been trying to add legend to my ggplot, but failed miserably. I tried the function scale_colour_manual()
, but the legend doesn\'t show up.
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.