我想在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)
Run Code Online (Sandbox Code Playgroud)
需要注意两点:
aes(color = XXX, ...)。创建单独的图例的一种解决方法是利用以下事实:某些形状(可以在中指定geom_point())可以同时具有fill美感和color美感。图片是从这里拍摄的。形状21-25接受color(以黑色表示)和fill(以红色表示)。
aes()。但是有时我们希望直接为每行指定颜色。一种解决方法是使用该scale_XXX_manual()选项,该选项使您可以aes(color = "some label")在geom中进行指定,并在scale_color_manual(values = c("some label" = "some color"))码:
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"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1209 次 |
| 最近记录: |