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")
Is it possible to add a scale or legend for the black line? Something like:
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)
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With