请考虑以下事项:
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")
是否可以为黑线添加比例或图例?类似的东西:
答案 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)
答案 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")