You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言ggalluvial包:strata排序、去标签边框及标签重叠解决

ggalluvial桑基图定制问题解决方法

问题1:按strata大小重排中间轴(bio drug name)

要让高count的strata(比如baricitinib)排在顶部,先统计每个生物药物的总count,再重新设置bio_drug_name的因子水平顺序:

# 计算每个药物的总count,按降序提取因子水平
drug_order <- allu4 %>%
  group_by(bio_drug_name) %>%
  summarize(total = sum(count)) %>%
  arrange(desc(total)) %>%
  pull(bio_drug_name)

# 重置因子水平
allu4$bio_drug_name <- factor(allu4$bio_drug_name, levels = drug_order)

问题2:标签重叠的解决办法

不用换ggsankey,直接用以下方案调整:

  • 把geom_label换成geom_text,去掉标签背景减少拥挤;
  • 缩小标签字号(比如从3调到2.5);
  • 安装ggrepel包后用geom_label_repel,自动调整标签位置避免重叠;
  • 微调geom_stratum的width参数,给标签留出更多空间。

问题3:移除strata的黑色边框

你代码里的geom_stratum设置了color = "black",直接删掉这个参数或者设为color = NA即可:

geom_stratum(alpha = 1, width = 1/5, fill = "#ffffff")  # 移除color参数

修改后的完整代码

library(dplyr)
library(ggplot2)
library(ggalluvial)
# 可选:用ggrepel解决标签重叠
# library(ggrepel)

# dummy dataset
btsd <- c("anticd20", "anticd20", "coi", "coi", "coi", "jaki", "jaki", "coi")
mult_conc2 <- c("mtx", "mtx", "none", "mtx", "multi", "mtx", "none", "multi")
cond_psoriasis <- c(0, 1, 1, 1, 0, 0, 1, 1)
bio_drug_name <- c("rituximab", "anakinra", "rituximab", "baricitinib", "etanercept", "etanercept", "ustekinumab", "guselkumab")
count <- c(5, 5, 4, 500, 3, 2, 2, 7)
allu4 <- data.frame(btsd, mult_conc2, cond_psoriasis, bio_drug_name, count)
rm("bio_drug_name", "btsd", "cond_psoriasis", "count", "mult_conc2")
cols <- c("btsd", "bio_drug_name", "mult_conc2", "cond_psoriasis")
allu4 <- allu4 %>% mutate_at(cols, factor)
rm(cols)

# 按总count排序bio_drug_name
drug_order <- allu4 %>%
  group_by(bio_drug_name) %>%
  summarize(total = sum(count)) %>%
  arrange(desc(total)) %>%
  pull(bio_drug_name)
allu4$bio_drug_name <- factor(allu4$bio_drug_name, levels = drug_order)

# 绘制桑基图
ggplot(as.data.frame(allu4),
       aes(y = count, axis1 = btsd, axis2 = bio_drug_name, axis3 = mult_conc2)) +
  geom_alluvium(aes(fill = bio_drug_name), width = 1/12) +
  # 移除strata黑色边框
  geom_stratum(alpha = 1, width = 1/5, fill = "#ffffff") +
  # 用geom_text减少标签重叠,或替换为geom_label_repel
  geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 2.5) +
  # 若用ggrepel:geom_label_repel(stat = "stratum", aes(label = after_stat(stratum)), size = 2.5)
  scale_x_discrete(limits = c("drug class", "bio drug name", "concomittant"), expand = c(0.1, 0.1)) +
  scale_fill_brewer(type = "qual", palette = "Set1") +
  guides(fill = "none") +
  ggtitle("b-tsDMARD, concommitant treatment and condition") +
  theme(legend.position = "none")

内容的提问来源于stack exchange,提问作者joejoe9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 21:56:06