ggalluvial图:流量百分比取整与标签位置调整需求
解决ggalluvial流量百分比的两个问题:固定小数位与标签重叠
问题说明
在绘制ggalluvial图并添加流量百分比时,遇到两个核心问题:
- 百分比的小数位数无固定规则,随空间自动调整,需要实现固定取整效果(如整数或指定小数位数)
- 百分比标签与ggrepel生成的地层标注线重叠,需要微调标签的x轴位置规避冲突
数据准备
allu5 = data.frame(mult_conc2 = as.factor(c("mtx", "mtx", "none", "mtx", "multi", "mtx", "none", "multi")), cond_psoriasis = as.factor(c(0, 1, 1, 1, 0, 0, 1, 1)), bio_drug_name = as.factor(c("rituximab", "anakinra", "rituximab", "baricitinib", "etanercept", "etanercept", "ustekinumab", "guselkumab")), count = c(50, 50, 40, 70, 30, 25, 25, 70)) colorfill = c("tomato4", "tomato3", "tomato2", "tomato1", "tomato", "turquoise", "yellow2", "steelblue1", "springgreen", "snow3", "slategray2", "red1", "purple", "plum1", "olivedrab2")
修改后的完整代码
library(ggplot2) library(ggalluvial) ggplot(allu5, aes(y = count, axis1 = bio_drug_name, axis2 = mult_conc2)) + geom_alluvium(aes(fill = bio_drug_name), width = 1 / 12) + geom_stratum(alpha = 1, width = 1 / 5, fill = "#ffffff", color = "black") + ggrepel::geom_label_repel(stat = "stratum", aes(label = after_stat(stratum)), size = 6, direction = "y", nudge_x = .25, label.size = 0) + scale_x_discrete(limits = c("bio drug name", "concomitant"), expand = c(0.1, 0.1)) + scale_fill_manual(values = colorfill) + guides(fill = "none") + ggtitle("b-tsDMARD, concommitant treatment and condition") + theme(legend.position = "none") + # 解决两个问题的核心改动 geom_text(stat = "flow", aes(label = scales::percent(after_stat(count)/after_stat(max(ymax)), accuracy = 1), hjust = after_stat(flow) == "to"), nudge_x = ifelse(after_stat(flow) == "to", 0.1, -0.1))
关键改动解释
固定百分比小数位
在scales::percent()函数中添加accuracy参数:accuracy = 1:强制显示整数百分比accuracy = 0.1:保留1位小数,以此类推
彻底解决小数位数随机变化的问题。
避免标签重叠
通过nudge_x结合after_stat(flow)判断流向,实现差异化偏移:- 当流向为
"to"(指向右侧地层)时,标签向右偏移0.1 - 当流向为
"from"(指向左侧地层)时,标签向左偏移0.1
让标签主动远离地层标注线,彻底解决重叠问题。
- 当流向为
内容的提问来源于stack exchange,提问作者joejoe9
相关产品推荐
相关产品推荐

