求助:用ggplot2生成WT在前Mutant在后的双组水平条形图
问题背景
原本希望在同一水平条形图中展示基因数量(Gene number)与富集倍数(Enrichment fold change),初始数据如下:
| 名称 | Genes | Enrichment fold change |
|---|---|---|
| cellular process | 10 | 2 |
| Biological phase | 5 | 5 |
| cell process | 8 | 9 |
但生成的图表未适配右侧轴,于是更新数据为WT和Mutant两组的基因数量:
| 名称 | WT | Mutant |
|---|---|---|
| cellular process | 200 | 2 |
| Biological phase | 150 | 5 |
| cell process | 100 | 9 |
使用以下R代码生成了分面堆叠条形图,但不符合需求,需要将WT放在前、Mutant放在后:
library(tidyverse) df <- read.table(text = "Name WT Mutant 'cellular process' 200 2 'Biological phase' 150 5 'cell process' 100 9", header = TRUE) df %>% pivot_longer(-Name) %>% ggplot(aes(x = Name, y = value, fill = name)) + geom_col(position = position_stack()) + coord_flip() + facet_wrap(~name)
解决方案
调整WT与Mutant的堆叠顺序(取消分面)
原代码的facet_wrap(~name)会将WT和Mutant分成两个子图,不符合“同一条形图”的需求。要让WT在前、Mutant在后堆叠展示,需通过因子指定分组顺序,同时移除分面:
library(tidyverse) df <- read.table(text = "Name WT Mutant 'cellular process' 200 2 'Biological phase' 150 5 'cell process' 100 9", header = TRUE) df %>% pivot_longer(-Name) %>% # 将name转为因子,指定WT为第一层级 mutate(name = factor(name, levels = c("WT", "Mutant"))) %>% ggplot(aes(x = Name, y = value, fill = name)) + geom_col(position = position_stack()) + coord_flip() + # 同步图例顺序与堆叠顺序 scale_fill_discrete(limits = c("WT", "Mutant"))
回到初始需求:同一水平条形图展示基因数量与富集倍数(双Y轴)
如果你的核心需求是同时展示基因数量和富集倍数,可通过双Y轴实现,解决轴适配问题:
library(tidyverse) # 加载初始数据 df <- read.table(text = "Name Genes Enrichment_fold_change 'cellular process' 10 2 'Biological phase' 5 5 'cell process' 8 9", header = TRUE) ggplot(df, aes(x = Name)) + # 左侧Y轴:基因数量(水平条形) geom_col(aes(y = Genes), fill = "#619CFF", width = 0.6) + # 右侧Y轴:富集倍数(用点标记,需缩放匹配左侧轴范围) geom_point(aes(y = Enrichment_fold_change * 2), color = "#F8766D", size = 3) + coord_flip() + # 设置双Y轴,将缩放后的值还原为实际富集倍数 scale_y_continuous( name = "Gene number", sec.axis = sec_axis(~./2, name = "Enrichment fold change") ) + theme_minimal() + labs(x = "Functional category")
说明:代码中Enrichment_fold_change * 2是为了让富集倍数的刻度与基因数量的刻度范围匹配,你可以根据实际数据调整缩放比例,保证图表展示协调。
内容的提问来源于stack exchange,提问作者Venkata Narasimha Kadali
相关产品推荐
相关产品推荐

