-1

I am trying plot this data, and the line graph is correct, but I can't make the legend show up. Any thoughts?

ggplot(data, aes(x=time_months, size=I(1))) +geom_line(aes(y=monthly_net_revenue, color=I("blue"))) +
    geom_line(aes(y=cumsum(discounted_monthly_net_revenue), color=I("purple"))) +
    geom_line(aes(y=monthly_expenses, color=I("red"))) +
    geom_line(aes(y=cumsum(monthly_revenue), color=I("green")))
markus
  • 25,843
  • 5
  • 39
  • 58
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. Right now we can't see what your plot looks like – MrFlick Jan 17 '20 at 20:48

1 Answers1

2

This will probably work for you

ggplot(data, aes(x=time_months, size=I(1))) +
    geom_line(aes(y=monthly_net_revenue, color="blue")) +
    geom_line(aes(y=cumsum(discounted_monthly_net_revenue), color="purple")) +
    geom_line(aes(y=monthly_expenses, color="red")) +
    geom_line(aes(y=cumsum(monthly_revenue), color="green")) + 
    scale_color_identity(guide = "legend")

The scale_color_identity() uses the values you pass to color= directly as the color rather than treating them like a group name. You don't need I() with this method.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Not sure if OP will need it but perhaps you could add that the argument `guide = "legend"` is needed to show the legend. – markus Jan 17 '20 at 20:56
  • @markus Where do you suggest putting that parameter? Won't the guide automatically show up if done like this? – MrFlick Jan 17 '20 at 21:00
  • 1
    The default is `guide = "none"` in `scale_color_identity()` - which makes totally sense but OP stated that they can't make the legend show up. That's why I commented. – markus Jan 17 '20 at 21:01
  • 1
    @markus Ahh. I see what you are saying. Yes. Forgot that detail. It's much easier to test when sample data is included! – MrFlick Jan 17 '20 at 21:02