Adding legend to ggplot2 with multiple lines in a plot
I would really appreciate help with this. I totally don't understand how ggplot2 thinks about legends!
The chart is based on the following data frame called "meltdf":
xval variable value
1 0.000000 Shortfall Risk 100.00
2 4.624457 Shortfall Risk 99.83
3 9.179656 Shortfall Risk 60.96
4 13.742579 Shortfall Risk 36.29
5 18.620338 Shortfall Risk 27.71
6 22.947704 Shortfall Risk 22.52
7 27.690638 Shortfall Risk 19.72
8 32.174379 Shortfall Risk 17.89
9 36.637940 Shortfall Risk 15.79
10 41.107962 Shortfall Risk 15.96
11 45.644065 Shortfall Risk 15.97
The graph looks like this:
ggplot(data=meltdf,aes(x=xval,y=value))+
geom_line(size=1,colour=rgb(69,99,111,max=255))+
geom_vline(xintercept = 22 ,colour="darkgray")+
geom_vline(xintercept = 30 ,colour="darkred")+
theme_bw()+
labs(title="Shortfall Risk versus Investment Risk, Meeting Expenditure Only")+
theme(legend.position="bottom",
legend.text = element_text(size=9),
axis.text = element_text(size=9),
axis.title = element_text(size=9),
plot.title=element_text(size = 9),
legend.title=element_text(size=9))+
labs(x="Largest Historical Decline (%)", y="Probability of Shortfall (%)")+
scale_y_continuous(limits = c(0, 100))
I would like to have a legend at the bottom where all three lines in the diagram (blue, red and gray) are named.
ggplot will automatically generate a legend for the elements (colors, linetypes, etc.) that are displayed within the call aes()
. This means you won't get the legend when you manually specify the color of the element like you are here (all your statements colour
are not inside aes
).
I recommend that you store the coordinates of your vertical lines in your own dataframe, where they can be mapped to a variable giving their color. Here I am creating such a data file ( summ
) and rewriting your code for geom_vline()
. I also matched meltdf$variable
with colour
in geom_vline
, so it appears in the legend. Finally, I added scale_colour_manual()
to select colors. You might want to adapt the meaning summ$colour
so that it makes sense in the legend.
summ <- data.frame(x=c(22,30),
colour=c("gray","red"))
ggplot(data=meltdf,aes(x=xval,y=value))+
geom_line(size=1,aes(colour=variable))+
geom_vline(data=summ,aes(xintercept = x,colour=colour))+
scale_color_manual(values = c(rgb(69,99,111,max=255),"darkgray","darkred")) +
theme_bw()+
labs(title="Shortfall Risk versus Investment Risk, Meeting Expenditure Only")+
theme(legend.position="bottom",
legend.text = element_text(size=9),
axis.text = element_text(size=9),
axis.title = element_text(size=9),
plot.title=element_text(size = 9),
legend.title=element_text(size=9))+
labs(x="Largest Historical Decline (%)", y="Probability of Shortfall (%)")+
scale_y_continuous(limits = c(0, 100))