You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在直方图上叠加分组密度曲线:如何移除图例中的密度标记?(ggplot2, R)

解决ggplot图例方块的蓝色粗边框问题

直接给geom_density()加上show.legend = FALSE参数就能解决这个问题,修改后的完整代码如下:

require(ggplot2)

mtcars$am2 <- factor(mtcars$am)
p1 <- ggplot(mtcars, aes(x = mpg, y = ..density.., fill = am2)) +
  geom_histogram(position = "identity", alpha = 0.8, colour = 1, bins = 12)+
  scale_fill_manual(values = c( "pink", "lightgrey")) +
  theme(
    legend.position = "bottom"
  )

p1 +
  geom_density(colour = "blue", lwd = 2, inherit.aes = F, 
               aes(x = mpg, y = ..density.., group = am2),
               show.legend = FALSE)  # 新增参数阻止该图层影响图例

原因说明

你之前的代码里,geom_density指定了group = am2,即便设置了inherit.aes = FALSE,ggplot依然会把这个图层的视觉元素(蓝色粗线)加入到图例的方块边框里。加上show.legend = FALSE后,这个图层就不会参与图例的构建,图例只会保留对应直方图填充色的方块,蓝色边框自然就消失了。

内容的提问来源于stack exchange,提问作者Reader 123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:35:22