Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a legend to geom_smooth that does not have an aes aesthetic call

Tags:

r

ggplot2

Consider the following:

library(ggplot2)

ggplot(mtcars, aes(disp, mpg)) +
  geom_point(aes(color = factor(cyl))) +
  geom_smooth(aes(color = factor(cyl)), se = FALSE, method = "lm") +
  geom_smooth(se = FALSE, method = "lm", fullrange = TRUE, color = "black")

Plot

Is it possible to add a scale or legend for the black line? Something like:

Desired Results

like image 952
JasonAizkalns Avatar asked Jan 13 '17 20:01

JasonAizkalns


2 Answers

Just add another aes mapping in the second geom_smooth() call:

p <- ggplot(mtcars, aes(disp, mpg)) +
     geom_point(aes(color = factor(cyl)), show.legend = FALSE) +
     geom_smooth(aes(color = factor(cyl)), se = FALSE, method = "lm") +
     geom_smooth(se = FALSE, method = "lm", fullrange = TRUE,
                 aes(color = "all data")) +
     scale_color_manual(values = c(scales::hue_pal()(3), "black"))
print(p)

plot

like image 175
rcs Avatar answered Sep 28 '22 08:09

rcs


The legend for all data can be separated out from the cyl color legends with the following trick with scale_fill_identity and using fill instead of color for the all-data geom_smooth:

ggplot(mtcars, aes(disp, mpg, color = factor(cyl))) +
  geom_point() +
  geom_smooth(se = FALSE, method = "lm") +
  geom_smooth(data=mtcars, aes(disp, mpg, fill = 'black'), se = FALSE, method = "lm", color='black') + 
  scale_fill_identity(name = '', guide = 'legend',labels = c('all data'))

enter image description here

like image 23
Sandipan Dey Avatar answered Sep 28 '22 08:09

Sandipan Dey