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

ggalluvial绘图:分层框排序、线条宽度与高度设置问题

ggalluvial绘图样式调整方案

问题1:按domain归类排序第一个轴(disease)

要让disease按domain分组,且顺序和图例一致,需先将disease转换为因子类型,并根据domain的顺序指定因子水平:

# 确定domain的顺序(与图例一致)
domain_order <- unique(data$domain)
# 按domain分组排序disease,生成因子水平
disease_order <- data %>% 
  arrange(match(domain, domain_order)) %>% 
  pull(disease) %>% 
  unique()
# 将disease转为因子
data$disease <- factor(data$disease, levels = disease_order)

处理后第一个轴的disease会按domain归类排列,且与图例的domain顺序匹配。

问题2:缩小冲积线条宽度

直接调整geom_alluvium的width参数(控制冲积带的宽度),将原参数值改小即可,示例如下:

geom_alluvium(aes(fill = domain), curve_type = "linear", width=0.3)

问题3:设置分层框的最小/最大高度

在geom_stratum中添加min.height和max.height参数,限制分层框的高度范围,避免过窄或过宽:

geom_stratum(alpha = .5, width=0.8, min.height=5, max.height=20)

完整修改后代码

library(ggplot2)
library(ggalluvial)
library(dplyr)

# 原始数据
data <- data.frame(person = c(rep("x",5), rep("y",2), rep("z",4), rep("w",2), rep("v",7)),    
                  disease = c("ADHD", "Depression", "Phobia", "Schizophrenia", "Bipolar"),
                  marker1 = c(sample(paste("cz",1:15, sep="")), "cz4", "cz5", "cz10", "cz1", "cz3"),
                  marker2 = rep(paste("ab",1:10,sep=""), 2),
                  domain = c("Development", "Mood", "Anxiety", "Psychiatric", "Psychiatric"),
                  freq = 1)

# 按domain排序disease
domain_order <- unique(data$domain)
disease_order <- data %>% 
  arrange(match(domain, domain_order)) %>% 
  pull(disease) %>% 
  unique()
data$disease <- factor(data$disease, levels = disease_order)

# 绘图代码
ggplot(data = data,
       aes(axis1 = disease,   
           axis2 = person, 
           axis3 = marker1,
           axis4 = marker2,
           y = freq)) +
  geom_alluvium(aes(fill = domain), curve_type = "linear", width=0.3) + 
  geom_stratum(alpha = .5, width=0.8, min.height=5, max.height=20) + 
  geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
  theme_void()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 13:10:08