我想在 ggplot 散点图上有两个图例:一个用于点颜色,另一个用于回归线颜色。
您能解释一下如何在此处为两条回归线添加单独的图例吗?
ggplot(mtcars, aes(x = mpg, y = hp)) +
geom_point(aes(color = gear)) +
geom_smooth(method='lm', formula=y~x, se = FALSE, size = 0.5, color = 'dark green') +
geom_smooth(method='lm', aes(mpg, hp), data = mtcars[mtcars$wt > 3, ], se = FALSE, size = 0.5, color = 'dark orange', fullrange = TRUE)
最佳答案
有两点需要注意:
- 默认情况下,ggplot 将根据指定
aes(color = XXX, ...)
的所有几何图形,为每种映射美学仅生成一个图例。创建单独图例的一种解决方法是利用以下事实:某些形状(可以在geom_point()
中指定)可以呈现fill
美学以及>颜色
审美。
图片取自 here 。形状 21-25 接受 color
(以黑色表示)和 fill
(以红色表示)。
- 为了创建图例,必须在内部
aes()
指定美观。但有时我们希望直接为每条线指定颜色。一种解决方法是使用scale_XXX_manual()
选项,该选项允许您在 geom 中指定aes(color = "some label")
,并在中映射颜色>scale_color_manual(values = c("某些标签"= "某些颜色"))
代码:
ggplot(mtcars,
aes(x = mpg, y = hp)) +
geom_point(aes(fill = gear), shape = 21) + # specify shape here
geom_smooth(method = 'lm', formula = y~x,
se = FALSE, size = 0.5,
aes(color = "lm1")) + # specify color within aes()
geom_smooth(method = 'lm', se = FALSE, size = 0.5,
data = mtcars[mtcars$wt > 3, ],
aes(x = mpg, y = hp, color = "lm2"), # as above
fullrange = TRUE) +
scale_fill_continuous(name = "Points") + # legend name
scale_color_manual(name = "Regression", # legend name
values = c("lm1" = "darkgreen", # map regression line colors
"lm2" = "darkorange"))
关于r - ggplot回归线的单独图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48674022/