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

R语言ggplot绘制多分组非堆叠直方图与密度叠加图

需求与问题

需要在同一画布绘制3个重叠的半透明直方图(每组颜色不同),并叠加密度多边形。核心要求:

  • 直方图不自动堆叠不同分组的bins,每个分组独立计算密度后叠加展示,方便对比分布(不使用facet_wrap)
  • 当前可通过单独调用每个分组的geom_histogram实现,但分组较多时操作繁琐
  • 尝试用group参数分组处理,仍出现堆叠问题,希望批量实现该需求,用于分析个体分布、识别异常或子组

示例数据与测试代码

library(ggplot2)
library(dplyr)

# 模拟数据
color <- c("yellow", "brown", "green")
n_per_factor <- c(45, 50, 48)
flies <- c(rgamma(n_per_factor[1], shape = 40, scale = 3.5),
           rgamma(n_per_factor[2], shape = 40, scale = 3),
           rgamma(n_per_factor[3], shape = 40, scale = 2.5))
bananas <- data.frame(color = rep.int(color, times = n_per_factor),
                      flies = flies)

1. 自动堆叠的直方图(不满意的效果)

此代码生成堆叠直方图,不符合需求:

ggplot(data = bananas, aes(x = flies, after_stat(density), 
                           fill = color))+
  geom_histogram(alpha = 0.50)+
  geom_density(alpha = 0.50)+
  xlab("每个香蕉上的果蝇数量")+
  ylab("密度")

效果:
不满意的堆叠直方图

2. 手动逐个分组绘制(满意但繁琐)

通过单独过滤每个分组调用geom_histogram可实现重叠效果,但分组多时代码冗余:

ggplot(data = bananas, aes(x = flies, after_stat(density), 
                           fill = color))+
  geom_histogram(data = bananas %>% filter(color == "yellow"),
                 aes(x = flies, after_stat(density), 
                     fill = color), alpha = 0.50)+
  geom_histogram(data = bananas %>% filter(color == "green"),
                 aes(x = flies, after_stat(density), 
                     fill = color), alpha = 0.50)+
  geom_histogram(data = bananas %>% filter(color == "brown"),
                 aes(x = flies, after_stat(density), 
                     fill = color), alpha = 0.50)+
  geom_density(alpha = 0.50)+
  xlab("每个香蕉上的果蝇数量")+
  ylab("密度")

效果:
满意的重叠直方图

3. 尝试失败的代码

使用group参数仍无法避免堆叠:

ggplot(data = bananas, aes(x = flies, after_stat(density), 
                           group = color, fill = color))+
  geom_histogram(alpha = 0.50)+
  geom_density(alpha = 0.50)+
  xlab("每个香蕉上的果蝇数量")+
  ylab("密度")

批量实现的解决方案

只需在geom_histogram中添加position = "identity"参数,即可让所有分组的直方图独立重叠绘制,无需手动逐个分组调用:

ggplot(data = bananas, aes(x = flies, after_stat(density), 
                           fill = color))+
  geom_histogram(alpha = 0.50, position = "identity", bins = 15)+ # 核心参数position=identity,可调整bins优化展示
  geom_density(alpha = 0.2, color = NA)+ # 调整密度图透明度避免遮挡
  xlab("每个香蕉上的果蝇数量")+
  ylab("密度")+
  theme_minimal()

说明:

  • position = "identity"是关键,让每个分组的直方图直接重叠,不进行堆叠或错位排列
  • 可通过bins参数调整直方图分箱数量,让分布对比更清晰
  • 密度图的透明度、边框样式可按需调整,平衡展示效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:36:09