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

如何使用ggdensity叠加总密度图与分组密度图

解决方法

你直接用+连接两个ggdensity()会生成两张独立的图,因为每个ggdensity()都是完整的ggplot对象。要把总密度和分组密度叠加在同一图里,有两种简单的实现方式:

方法一:基于ggpubr快速实现

利用ggdensity先画出分组密度图,再手动添加总密度和总均值的图层:

library(ggpubr)

ggdensity(iris, x = "Sepal.Length", add = "mean", rug = TRUE,
          color = "Species", fill = "Species", alpha = 0.3) +
  # 添加总数据集的密度曲线
  geom_density(data = iris, aes(x = Sepal.Length), color = "black", size = 1) +
  # 添加总数据的均值线
  geom_vline(data = iris, aes(xintercept = mean(Sepal.Length)), 
             color = "black", linetype = "dashed", size = 1)

设置alpha=0.3是为了让分组密度的填充色半透明,不会遮挡总密度曲线。

方法二:用原生ggplot2自定义(更灵活)

如果需要更精细控制图中元素的样式,直接用ggplot2的基础图层组合:

library(ggplot2)

ggplot() +
  # 绘制分组密度图,设置半透明填充
  geom_density(data = iris, aes(x = Sepal.Length, color = Species, fill = Species), 
               alpha = 0.3) +
  # 绘制总密度曲线(黑色粗线)
  geom_density(data = iris, aes(x = Sepal.Length), color = "black", size = 1) +
  # 添加分组的均值虚线
  stat_summary(data = iris, aes(x = Sepal.Length, color = Species), 
               fun = mean, geom = "vline", linetype = "dashed") +
  # 添加总数据的均值实线
  geom_vline(xintercept = mean(iris$Sepal.Length), color = "black", 
             linetype = "solid", size = 1) +
  # 添加rug图
  geom_rug(data = iris, aes(x = Sepal.Length, color = Species)) +
  # 可选:设置简洁主题
  theme_bw()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:10:28