如何移除ggplot中geom_smooth置信区间在图例中的灰色框?
移除ggplot图例中geom_smooth置信区间的灰色框
问题描述
我结合geom_point()与geom_smooth(),通过包含3个分组的cj变量手动控制颜色,代码整体运行正常,但图例中每个点线组合周围出现灰色框,推测该灰色框来自geom_smooth的置信区间(SE),希望移除该灰色框,仅保留图例中的彩色点和线。
原代码:
ggplot(d, aes(x = month, y = prop_er, color = cj, fill = cj)) + geom_point() + geom_smooth(se = TRUE, method = "lm", aes(fill = cj), alpha = 0.3) + facet_grid(cols = vars(age), rows = vars(pers)) + scale_color_manual(values = colors, labels = group) + scale_fill_manual(values = colors, guide = "none") + theme_minimal() + theme(legend.position = "bottom")
解决方案
有两种简单有效的方法可以解决这个问题:
方法一:让geom_smooth不渲染图例元素
在geom_smooth()中添加show.legend = FALSE参数,这样它的置信区间填充就不会出现在图例里,而geom_point()的点和全局color映射的线条会正常保留在图例中:
ggplot(d, aes(x = month, y = prop_er, color = cj, fill = cj)) + geom_point() + geom_smooth(se = TRUE, method = "lm", aes(fill = cj), alpha = 0.3, show.legend = FALSE) + # 添加该行参数 facet_grid(cols = vars(age), rows = vars(pers)) + scale_color_manual(values = colors, labels = group) + scale_fill_manual(values = colors, guide = "none") + theme_minimal() + theme(legend.position = "bottom")
方法二:覆盖图例的填充属性
通过guides()函数强制图例中的填充为透明(NA),直接去掉灰色框:
ggplot(d, aes(x = month, y = prop_er, color = cj, fill = cj)) + geom_point() + geom_smooth(se = TRUE, method = "lm", aes(fill = cj), alpha = 0.3) + facet_grid(cols = vars(age), rows = vars(pers)) + scale_color_manual(values = colors, labels = group) + scale_fill_manual(values = colors, guide = "none") + guides(color = guide_legend(override.aes = list(fill = NA))) + # 添加该行覆盖属性 theme_minimal() + theme(legend.position = "bottom")
两种方法都能达到预期效果,可根据个人习惯选择。
内容的提问来源于stack exchange,提问作者user14212134
相关产品推荐
相关产品推荐

