Search code examples
rggplot2legendlinegraph

Using ggplot2 in R and a legend will not show up in my figure. Why is that?



View(PV)                                                                

library(ggplot2)

ssplot <- ggplot(PV, aes(x=year)) + geom_line(aes(y = infinite_horizon), color = "darkred", size = 1) + geom_line(aes(y = through_year_75), color="steelblue", size = 1)

print(ssplot + labs(y="Present Value ($, trillions)", x = "Year") + ggtitle("Measures of Unfunded Social Security Obligations, 2003-2020"))

Unfortunately, I can't post images yet, but I'm getting a figure with two lines and no legend. Why is this the case? Any help would be appreciated. Thanks.


Solution

  • set the color in the aes() and use scale_color_manual() to set the color manually

    ggplot(PV, aes(x = year)) + 
      geom_line(aes(y = infinite_horizon, color = "darkred"), size = 1) + 
      geom_line(aes(y = through_year_75, color="steelblue"), size = 1) +
      scale_color_manual(values = c("steelblue" = "steelblue", "darkred" = "darkred"))