0

The problem I am trying to solve is to include two legends within a ggplot.

I can generate the first legend automatically, however I have had no luck trying to generate the second legend manually.

Consider the following example:

library(tidyverse)

(pp <- mtcars %>% 
  # filter(mpg > 13, mpg < 20) %>% 
  ggplot(aes(x = mpg, y = disp)) + 
  geom_col(aes(fill = disp)) +

  geom_point(aes(y = hp, group = 1), stat = "summary", fun.y = sum)+
  stat_summary(aes(y = hp, group = 1), fun.y = sum, geom = "line", size = 1, colour = "red")

)

In the above plot I want to include a legend that says red line is hp

How do I go about doing this?

cephalopod
  • 1,826
  • 22
  • 31
  • 1
    Map the string `"red line is hp"` to `color` inside `aes` in `stat_summary()` and add `+ scale_color_manual(value = c("red line is hp" = "red")` to your plot. – markus Dec 03 '19 at 22:05
  • Thanks it worked! – cephalopod Dec 03 '19 at 22:24
  • `mtcars %>% ggplot(aes(x = mpg, y = disp)) + geom_col(aes(fill = disp)) + geom_point(aes(y = hp, group = 1), stat = "summary", fun.y = sum)+ stat_summary(aes(y = hp, group = 1, colour = "hp"), fun.y = sum, geom = "line", size = 1) + scale_colour_manual(values = c("hp" = "red"), name = "")` – cephalopod Dec 03 '19 at 22:33

0 Answers0