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

能否用ggplot在R中绘制带侧边分布的分组条形图?

带分布展示的分组条形图实现(R语言)

图形名称

这种将分组条形图(展示汇总统计,如均值)与分布类图形(展示数据分布细节,如密度、箱线、小提琴图)结合的可视化,通常被称为带边际分布的分组组合图,核心是同时呈现整体汇总和个体数据的分布特征。

R语言实现方案

可以用ggplot2包灵活实现,以下提供两种常见思路:

思路1:在条形右侧直接叠加密度图

通过调整坐标映射,将密度图对齐到对应条形的右侧,同时设置透明度提升可读性:

# 加载所需包
library(ggplot2)
library(dplyr)

# 模拟某一年份的男女收入数据
set.seed(123)
data <- tibble(
  gender = rep(c("男性", "女性"), each = 500),
  income = c(rnorm(500, 8000, 1500), rnorm(500, 7000, 1200))
)

# 计算男女收入均值(条形图高度)
summary_data <- data %>% 
  group_by(gender) %>% 
  summarise(mean_income = mean(income))

# 绘图
ggplot() +
  # 绘制分组条形图
  geom_bar(data = summary_data, 
           aes(x = gender, y = mean_income, fill = gender),
           stat = "identity", width = 0.5) +
  # 叠加密度图,调整位置到条形右侧,设置透明度
  geom_density(data = data, 
               aes(x = income, y = after_stat(scaled) * 0.4 + as.numeric(gender) - 1.2),
               fill = "grey", alpha = 0.3, color = NA) +
  # 设置男女条形颜色
  scale_fill_manual(values = c("男性" = "green", "女性" = "red")) +
  # 坐标轴与标题设置
  labs(x = "性别", y = "收入", title = "男女收入均值及分布对比") +
  theme_minimal() +
  theme(legend.position = "none")

代码说明:

  • after_stat(scaled) 将密度值标准化,确保和条形图的坐标范围匹配;
  • as.numeric(gender) 把性别转为数值,用来对齐密度图的垂直位置;
  • alpha = 0.3 降低密度图透明度,避免遮挡条形图。

思路2:用拼图工具分开绘制再组合

如果希望布局更灵活,可以用cowplot包将条形图和分布图左右拼接:

library(cowplot)

# 绘制条形图
bar_plot <- ggplot(summary_data, aes(x = gender, y = mean_income, fill = gender)) +
  geom_bar(stat = "identity", width = 0.5) +
  scale_fill_manual(values = c("男性" = "green", "女性" = "red")) +
  labs(x = "性别", y = "收入均值") +
  theme_minimal() +
  theme(legend.position = "none")

# 绘制分面密度图
density_plot <- ggplot(data, aes(x = income, fill = gender)) +
  geom_density(alpha = 0.3) +
  scale_fill_manual(values = c("男性" = "green", "女性" = "red")) +
  facet_wrap(~gender, ncol = 1) +
  labs(x = "收入分布", y = "密度") +
  theme_minimal() +
  theme(legend.position = "none")

# 拼接图形
plot_grid(bar_plot, density_plot, rel_widths = c(1, 1.5))

如果偏好箱线图或小提琴图展示分布,只需将geom_density替换为geom_boxplot或geom_violin,调整对应参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:42:49