我知道这个问题已经被问过很多次了,但我仍然找不到一个好的答案。我想要一个漂亮的图例,在绘图上的单独图例中显示手动添加的线条。这是我到目前为止所想到的:
library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10))) +
geom_abline(aes(intercept=25, slope = (-1/30)))
给出:
其中有手动添加的行,但没有它们的图例条目。
尝试 1
仅添加 show.legend=TRUE
并没有多大帮助:
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10)), show.legend = TRUE) +
geom_abline(aes(intercept=25, slope = (-1/30)), show.legend = TRUE)
尝试 2
为每个附加行添加人工填充
也不是很有帮助:
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10), fill='Comparison Line 1')) +
geom_abline(aes(intercept=25, slope = (-1/30), fill='Comparison Line 2'))
它只是给出警告并返回原始图:
Warning: Ignoring unknown aesthetics: fill
Warning: Ignoring unknown aesthetics: fill
尝试 3
同时添加 show.legend=TRUE
和假 aes fill
效果很接近,但结果非常难看:
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10), fill='Comparison Line 1'), show.legend = TRUE) +
geom_abline(aes(intercept=25, slope = (-1/30), fill='Comparison Line 2'), show.legend = TRUE)
最后,我的问题:
如何去掉颜色图例中的对角线(标题为“factor(am)”),以及如何在填充图例(标题为“fill”)中的项目旁边获得看起来正常的线条?
最佳答案
你们非常接近!
添加与 geom_abline
相关的虚拟变量例如size
至aes()
。和规模size
返回使用 scale_size_manual
.
library(ggplot2)
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10), size='Comparison Line 1')) +
geom_abline(aes(intercept=25, slope = (-1/30), size='Comparison Line 2')) +
scale_size_manual(values = c(0.3, 0.3))
PS.:您使用的填充对于 abline 来说是未知的美学(如 ggplot2
警告您: Warning: Ignoring unknown aesthetics: fill
)。
关于r - 将手动添加的行包含到 ggplot2 指南图例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47044634/