如何使用ggplot2绘制y轴两侧分开展示的非堆叠分组条形图
问题原因
代码输出堆叠条形图,是两个关键步骤缺失导致的:
geom_bar()默认采用position = "stack"堆叠模式,同位置的多组条形会自动堆叠- 要实现y轴两侧分列的双向条形图,必须将其中一个分组的数值转为负值,否则两组都是正值无法分布在0基准线两侧
修正方案
- 绘图时将其中一组的表达量取负值,让两组数值分别落在0轴两侧
- 显式指定
geom_bar()的位置参数为position = "identity",关闭默认堆叠逻辑 - 调整y轴刻度标签,将负刻度转换为正数显示,符合常规阅读习惯
- 补充0基准线,明确分隔两侧分组
完整可运行修正代码
library(tidyverse) # 原始数据 Data <- structure(list(SampleID = c("Sample_1", "Sample_2", "Sample_3", "Sample_4", "Sample_5", "Sample_6"), Sustained_CR = c("NO", "NO", "NO", "YES", "YES", "YES"), Gene_A = c(2.245937679, 0, 0, 1.128343065, 0, 0), Gene_CCC = c(83.09969414, 16.10799215, 122.2752332, 57.54549633, 13.12780895, 62.70159708), Gene_XED = c(6.737813038, 1.006749509, 12.80978634, 1.128343065, 0, 2.508063883), RNA = c(580.5748901, 312.0923478, 347.0287571, 292.2408539, 355.7636226, 125.4031942 )), row.names = c("Sample_1", "Sample_2", "Sample_3", "Sample_4", "Sample_5", "Sample_6"), class = "data.frame") # 长格式转换、均值计算(和原有逻辑一致,补充.groups参数消除版本提示) Data_long <- Data[, -c(1)] %>% pivot_longer(cols = -"Sustained_CR",names_to="Gene_Symbols",values_to="Normalized expression values") Data_mean <- Data_long %>% group_by(Gene_Symbols, Sustained_CR) %>% summarize(Norm_exp=mean(`Normalized expression values`, na.rm = T), .groups = "drop") # 修正后的绘图代码 ggplot(Data_mean, aes( x = reorder(Gene_Symbols, Norm_exp, FUN = max), y = ifelse(Sustained_CR == "YES", -Norm_exp, Norm_exp), fill = Sustained_CR )) + geom_bar(stat = "identity", position = "identity", width = 0.7) + # 将y轴负刻度转为正数显示 scale_y_continuous(labels = function(x) abs(x)) + coord_flip() + # 添加中间0值基准线 geom_hline(yintercept = 0, linewidth = 0.5) + labs(x = "Gene_Symbols", y = "Normalized expression values", fill = "Sustained_CR") + theme_bw()
自定义调整提示
- 若要调换两个分组的左右展示位置,修改
ifelse(Sustained_CR == "YES", -Norm_exp, Norm_exp)里的分组判断逻辑,将NO组设为负值即可 - 若要调整基因排序规则,可以修改
reorder()内的排序函数,比如按两组表达量总和排序 - 可通过
scale_fill_manual()自定义两个分组的填充颜色,匹配目标可视化风格
效果对照
当前错误堆叠效果:
预期双向条形效果:
内容的提问来源于stack exchange,提问作者MOHAMMED TOUFIQ
相关产品推荐
相关产品推荐



