如何移除ggplot2柱状图图例中的多余蓝色线条?
解决ggplot2柱状图+LOESS平滑线图例冲突问题
问题根源在于geom_smooth图层默认会生成图例条目,与柱状图的fill图例发生重叠覆盖。以下是针对性解决方法:
方法一:隐藏平滑线的图例条目
将geom_smooth的show.legend参数设为FALSE(注意不要用已弃用的show_guide),这样就不会让平滑线的线条出现在图例中:
library(ggplot2) # 模拟示例数据 df <- data.frame( group = factor(rep(c("A", "B", "C"), each=10)), value = rnorm(30, mean=c(2, 4, 6)) ) # 修正后的代码 ggplot(df, aes(x=group, y=value, fill=group)) + geom_col(stat="summary", fun="mean") + # 绘制柱状图 geom_smooth(method="loess", aes(group=1), color="blue", show.legend=FALSE) # 添加LOESS线并隐藏其图例
方法二:单独控制不同美学属性的图例
如果你需要保留平滑线的图例,同时不影响柱状图的颜色显示,可以通过guides()函数分别配置fill(柱状图)和color(平滑线)的图例:
ggplot(df, aes(x=group, y=value, fill=group)) + geom_col(stat="summary", fun="mean") + geom_smooth(method="loess", aes(group=1, color="LOESS平滑线")) + # 给平滑线指定图例标签 guides( fill = guide_legend(title="分组"), color = guide_legend(title="拟合线") )
为什么你之前的尝试无效?
show_guide = F是ggplot2旧版本参数,现已被show.legend取代,所以旧参数不会生效;- 如果使用
override.aes时未明确指定对应美学元素(比如只处理了fill没处理color),会导致要么无效要么误删整个图例。
内容的提问来源于stack exchange,提问作者burzlboy
相关产品推荐
相关产品推荐

