Home > database >  How to add legend into ggplot with both by-group and combined effects?
How to add legend into ggplot with both by-group and combined effects?

Time:10-19

I'm trying to create a plot that has an overall effect from the regression as well as by-group effects for the same regression. As an example, I have used this plot for the mtcars dataset:

#### Group x Total Effect Plot ####
mtcars %>% 
  ggplot(aes(x=disp,
             y=wt)) 
  geom_point() 
  geom_smooth(method = "lm",
              se=F,
              color = "gray",
              aes(group=factor(am))) 
  geom_smooth(method = "lm",
              se=F)

Which looks like this:

enter image description here

However, I'd like to add a legend to the plot which is normal for by-factor aes functions in R, but I'm unsure of how to do this with the given example, as the total effect gets lost in the legend when I try:

#### Group by Total Effect Plot ####
mtcars %>% 
  ggplot(aes(x=disp,
             y=wt)) 
  geom_point() 
  geom_smooth(method = "lm",
              se=F,
              aes(color=factor(am))) 
  geom_smooth(method = "lm",
              se=F)

enter image description here

Is there a way I can artificially add the legend in some way? Or is there some workaround I'm not considering? My desired result is below:

enter image description here

CodePudding user response:

You can do something like this:

library(ggplot2)

mtcars |>
  ggplot(aes(x = disp, y = wt))  
  geom_point()  
  geom_smooth(
    aes(group = factor(am), colour = "Automatic/Manual Transmission"),
    method = "lm",
    se = FALSE
  )  
  geom_smooth(
    aes(colour = "Total Effect"),
    method = "lm", 
    se = FALSE
  )  
  scale_colour_manual(
    values = c(
      "Automatic/Manual Transmission" = "grey",
      "Total Effect" = "blue"
    )
  )  
  labs(colour = "Legend")
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'

Created on 2022-10-18 with reprex v2.0.2

  • Related