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

如何将ggplot+ggalluvial绘制的Alluvial Plot纵轴从频数改为百分比?

桑基图纵轴从频数改为百分比的实现方法

你可以通过调整ggalluvial图层的统计计算逻辑,直接将纵轴转换为百分比(基于每个位置的总观测数)。以下是针对你提供的模拟数据集的修改方案:

修改后的代码

library(ggplot2)
library(ggalluvial)
library(scales)

id <-  rep(1:15000, each = 7)
position <-  rep(1:7, 15000)
data <- data.frame(id,position)
data$class <- sample(1:4, nrow(data), replace = TRUE)

# 随机删除10%数据
data$random_number <- runif(nrow(data), 0, 1)
data <- data[data$random_number >= 0.1, ]

ggplot(data, aes(x = as.factor(position), 
                 stratum = as.factor(class), 
                 alluvium = as.factor(id),
                 fill = as.factor(class), 
                 label = as.factor(class))) +
  scale_fill_brewer(type = "qual", palette = "Set2") +
  scale_x_discrete(expand = c(.1, .1)) +
  # 为flow和stratum设置百分比统计
  geom_flow(aes(y = after_stat(100 * count / sum(count)))) +
  geom_stratum(aes(y = after_stat(100 * count / sum(count))), alpha = .5) +
  geom_text(stat = "stratum", 
            aes(y = after_stat(100 * count / sum(count))), 
            size = 3) +
  # 把纵轴设置为百分比格式
  scale_y_continuous(labels = percent_format(accuracy = 1)) +
  theme_bw() +
  theme(legend.position = "none", 
        axis.title.x = element_blank(),
        axis.title.y = element_text(label = "百分比"))

关键修改说明

  • 在geom_flow、geom_stratum和geom_text的aes中,通过after_stat(100 * count / sum(count))计算每个位置下各类别的占比(转换为百分比)
  • 使用scale_y_continuous配合scales::percent_format()将纵轴标签显示为百分比样式,accuracy参数控制小数位数
  • 恢复了纵轴标题,明确标注为“百分比”,也可以根据需要调整或隐藏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:15:07