0

I am trying to add a legend to my graphs in R using ggplot2 but have so far been unsuccessful. I have tried multiple different suggestions that I have seen online but none of them seem to produce a legend.

This is the code that I am using for my graphs (without trying to add a legend):

prrgapuk <- ggplot() + 
  geom_line(aes(y=uk1, x= Date), color="black", data = rrgap) +
  geom_line(aes(y=uk2, x= Date), color = "blue", linetype = "dotdash", data = rrgap) +
  geom_line(aes(y=uk3, x= Date), color = "red", linetype = "dashed", data = rrgap) +
  geom_line(aes(y=uk4, x= Date), color = "green", linetype="twodash", data = rrgap) +
  geom_line(aes(y=uk5, x= Date), color = "purple", linetype="longdash",data = rrgap) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
                                                                       panel.background = element_blank(), axis.line = element_line(colour = "black"))


prrgapuk + geom_hline(yintercept = 0, linetype="dotted") + labs(y="") + geom_rect(data = usrecessions.df, aes(xmin=Peak, xmax=Trough, ymin=-Inf, ymax=Inf), fill="grey", alpha=0.35) 

I would like the legend to look something like this

I would be really grateful if someone could point me in the right direction

  • What kind of legend do you want to add? can you provide an example? – elielink Aug 31 '21 at 13:59
  • 1
    You need to move `color` *inside* `aes()` to get a legend. :) I have a blog post about this topic in case it is useful [here](https://aosmith.rbind.io/2018/07/19/manual-legends-ggplot2/) but I know there are some good dupes on stack overflow on this, as well. – aosmith Aug 31 '21 at 14:01
  • 1
    Useful SO [answer here](https://stackoverflow.com/a/10355844/2461552) and another one [here](https://stackoverflow.com/questions/17148679/construct-a-manual-legend-for-a-complicated-plot). – aosmith Aug 31 '21 at 14:03
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 31 '21 at 14:54

0 Answers0