将图例添加到没有aes美学调用的geom_smooth

Jas*_*lns 4 r ggplot2

考虑以下:

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")
Run Code Online (Sandbox Code Playgroud)

情节

是否可以为黑线添加比例或图例?就像是:

期望的结果

rcs*_*rcs 6

只需aes在第二个geom_smooth()调用中添加另一个映射:

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)
Run Code Online (Sandbox Code Playgroud)

情节