求助:如何绘制按性别拆分的共享坐标轴垂直条形图
绘制按性别拆分的共享坐标轴垂直条形图(ggplot2)
首先你需要确保数据是长格式(每一行对应一个样本),结构大概包含三列:
category:类别列(M1、M2等)gender:性别列(比如"男"/"女")value:数值列(每个类别下的5个重复样本值)
步骤1:构造示例数据(匹配你的数据结构)
library(tibble) # 模拟数据:3个类别,每个类别男女各5个样本 df <- tibble( category = rep(c("M1", "M2", "M3"), each = 10), gender = rep(c("男", "女"), each = 5, times = 3), value = rnorm(30, mean = 20, sd = 3) # 生成无负值的随机数模拟你的数据 )
步骤2:绘制共享坐标轴的分组条形图
因为你有重复样本,更推荐展示分组均值(带误差棒);如果需要看单个样本,也可以直接绘制所有样本的条形:
方案1:展示每个类别男女的均值(带标准误误差棒)
library(ggplot2) ggplot(df, aes(x = category, y = value, fill = gender)) + geom_bar(stat = "summary", fun = "mean", position = position_dodge(width = 0.8), width = 0.7) + # 添加误差棒展示均值的标准误 geom_errorbar(stat = "summary", fun.data = "mean_se", position = position_dodge(width = 0.8), width = 0.2) + labs(x = "类别", y = "数值", fill = "性别") + theme_minimal()
方案2:展示所有样本的条形(查看单个样本分布)
ggplot(df, aes(x = interaction(category, gender), y = value, fill = gender)) + geom_bar(stat = "identity", position = "dodge") + # 拆分x轴标签,让类别和性别更清晰 scale_x_discrete(labels = function(x) gsub("\\.", "\n", x)) + labs(x = "类别-性别", y = "数值", fill = "性别") + theme_minimal()
关键参数说明
position = position_dodge(width = 0.8):让同一类别下的男女条形并列(而非堆叠),这是实现分组展示的核心stat = "summary":自动对每个分组(类别+性别)计算统计量(比如均值),无需手动提前汇总数据- 共享坐标轴是
ggplot2默认行为,只要将y映射到同一数值列,就会自动使用统一的y轴,无需额外设置
如果你的数据是宽格式(比如男、女各占一列),需要先转成长格式:
library(tidyr) # 示例宽格式数据 wide_df <- tibble( category = c("M1", "M2", "M3"), male_1 = rnorm(3,20,3), male_2 = rnorm(3,20,3), male_3 = rnorm(3,20,3), male_4 = rnorm(3,20,3), male_5 = rnorm(3,20,3), female_1 = rnorm(3,20,3), female_2 = rnorm(3,20,3), female_3 = rnorm(3,20,3), female_4 = rnorm(3,20,3), female_5 = rnorm(3,20,3) ) # 转换为长格式 long_df <- wide_df %>% pivot_longer(cols = -category, names_to = c("gender", "sample"), names_sep = "_", values_to = "value") %>% select(-sample)
转换后直接使用上面的绘图代码即可。
内容的提问来源于stack exchange,提问作者Alicia M
相关产品推荐
相关产品推荐

