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

时间:2017-01-13 20:48:18

标签: 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")

Plot

是否可以为黑线添加比例或图例?类似的东西:

Desired Results

2 个答案:

答案 0 :(得分:5)

只需在第二个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)

plot

答案 1 :(得分:2)

所有数据的图例可以与cyl颜色图例分开,其中scale_fill_identity使用fill代替color而不是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'))

user> (re-seq #"[^=]+|=" "asd=dfg=hgf=jjj")
;;=> ("asd" "=" "dfg" "=" "hgf" "=" "jjj")

user> (re-seq #"[^=]+|=" "asd=dfg=hgf=")
;;=> ("asd" "=" "dfg" "=" "hgf" "=")

user> (re-seq #"[^=]+|=" "=dfg=hgf=dffff")
;;=> ("=" "dfg" "=" "hgf" "=" "dffff")

enter image description here