r - 将手动添加的行包含到 ggplot2 指南图例中

标签 r plot ggplot2

我知道这个问题已经被问过很多次了,但我仍然找不到一个好的答案。我想要一个漂亮的图例,在绘图上的单独图例中显示手动添加的线条。这是我到目前为止所想到的:

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)))

给出:

enter image description here

其中有手动添加的行,但没有它们的图例条目。

尝试 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)  

enter image description here

尝试 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

enter image description here

尝试 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)

enter image description here

最后,我的问题:
如何去掉颜色图例中的对角线(标题为“factor(am)”),以及如何在填充图例(标题为“fill”)中的项目旁边获得看起来正常的线条?

最佳答案

你们非常接近!
添加与 geom_abline 相关的虚拟变量例如sizeaes() 。和规模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))

enter image description here

PS.:您使用的填充对于 abline 来说是未知的美学(如 ggplot2 警告您: Warning: Ignoring unknown aesthetics: fill )。

关于r - 将手动添加的行包含到 ggplot2 指南图例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47044634/

相关文章:

r - 询问如何在 R 中使用 ggplot 制作世界热图?

r - 如何使用summary_all获取与每个组的最大索引相关的非缺失值

r - 从混合模型 (lme4) 公式中提取成分

r - 如何增加轮廓标签的字体大小?

r - 通过行名和列名而不是数字来访问值

r - 如何更改 ggplot (geom_bin2d) 中箱的颜色以反射(reflect)该区域的密度与数据集中的平均密度之间的差异?

r - 在Docker Plumber中使用R预测包

r - 两个数据帧之间的值匹配

r - 使用 persp 的彩色图

r - 如何在 fiddle 图上显示 mustache 和点?