如何在配对堆叠柱状图的对应细胞组间添加连线?
问题:配对堆叠柱状图添加组间连线
我在绘制配对堆叠柱状图时遇到麻烦:没法在Pre和Post对应的细胞组之间添加连线。我要比较治疗前后(Pre→Post)的细胞组成变化,现在用下面的R脚本生成了普通堆叠柱状图,但想改成带连线的样式,作为新手,我搜过谷歌和Stack Overflow的示例,但没法把代码整合到自己的脚本里,求帮忙。
原代码:
data <- data.frame( Group = rep(c("Responder", "Non-responder"), each = 16), # 16 x 2 = 32 Time = rep(c("Pre", "Post"), times = 16), # 16 x 2 = 32 CellType = rep(c("B", "Mono", "DC", "CD4_T", "CD8_T", "NK", "Other", "Platelet"), each = 2, times = 2), # 길이 32 Proportion = runif(32, 0.01, 0.2) ) data <- data %>% group_by(Group, Time) %>% mutate(Proportion = Proportion / sum(Proportion)) %>% ungroup() # Stacked Bar Plot ggplot(data, aes(x = Time, y = Proportion, fill = CellType)) + geom_bar(stat = "identity", position = "stack") + # Stacked bar plot facet_wrap(~ Group, ncol = 2) + scale_fill_brewer(palette = "Paired") + theme_minimal() + labs( title = "Cell Type Proportions Before and After Treatment", x = "Time", y = "Cell Proportions", fill = "Cell Type" )
解决方案:添加连线的配对堆叠柱状图
要实现Pre与Post对应细胞组间的连线,核心是先计算每个细胞类型在堆叠图中的上下边界位置,再用geom_line连接对应位置的中点。以下是修改后的完整代码及关键解释:
修改后的完整代码
library(tidyverse) data <- data.frame( Group = rep(c("Responder", "Non-responder"), each = 16), Time = rep(c("Pre", "Post"), times = 16), CellType = rep(c("B", "Mono", "DC", "CD4_T", "CD8_T", "NK", "Other", "Platelet"), each = 2, times = 2), Proportion = runif(32, 0.01, 0.2) ) # 计算比例及堆叠位置参数 data <- data %>% group_by(Group, Time) %>% mutate( Proportion = Proportion / sum(Proportion), # 堆叠顶部位置:累积求和 y_end = cumsum(Proportion), # 堆叠底部位置:顶部位置减去当前比例 y_start = y_end - Proportion, # 取中间值作为连线的锚点,确保连线穿过细胞组中心 y_mid = (y_start + y_end) / 2 ) %>% ungroup() # 绘制带连线的堆叠柱状图 ggplot(data, aes(x = Time, y = Proportion, fill = CellType)) + # 堆叠柱状图主体 geom_bar(stat = "identity", position = "stack") + # 添加组间连线:按Group+CellType分组,连接Pre/Post的中点 geom_line(aes(y = y_mid, group = interaction(Group, CellType)), color = "black", linewidth = 0.5) + facet_wrap(~ Group, ncol = 2) + scale_fill_brewer(palette = "Paired") + theme_minimal() + labs( title = "治疗前后细胞类型比例变化", x = "时间点", y = "细胞比例", fill = "细胞类型" )
关键逻辑说明
- 计算堆叠位置:通过
cumsum(Proportion)得到每个细胞类型在堆叠柱中的顶部边界,再减去自身比例得到底部边界,取两者中点作为连线的锚点,保证连线精准对应到每个细胞组的中心。 - 连线分组:用
interaction(Group, CellType)作为group参数,确保每个分组内的同一细胞类型,能在Pre和Post两个时间点之间建立唯一的连线。
内容的提问来源于stack exchange,提问作者juyong seong
相关产品推荐
相关产品推荐

