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

如何在R中制作末端带数值或柱状图的流向图?

多维度分组流向图实现方案

需要安装并加载的包

除你已有的包外,还需ggalluvial(专门绘制流向/冲积图)和ggplot2:

install.packages(c("ggalluvial", "ggplot2"))
library(ggalluvial)
library(ggplot2)

方案1:显示分组均值数值(快速实现)

基于你生成的fit数据框,直接绘制流向图并标注每个分组的均值:

ggplot(fit,
       aes(y = proportion, axis1 = K, axis2 = A, axis3 = Q, axis4 = defense)) +
  geom_alluvium(aes(fill = defense), width = 1/12) +
  geom_stratum(width = 1/12, fill = "white", color = "black") +
  geom_text(stat = "stratum", aes(label = round(proportion, 2))) +
  scale_x_discrete(limits = c("K", "A", "Q", "Defense"), expand = c(0.05, 0.05)) +
  scale_fill_brewer(type = "qual", palette = "Set1") +
  labs(title = "K-A-Q-Defense 流向图(标注均值)",
       x = "分组维度", y = "均值比例") +
  theme_minimal()
  • 核心参数说明:
    • axis1-axis4按流向顺序对应你的四个分组维度
    • geom_alluvium绘制分组间的流向连接带
    • geom_stratum绘制每个分组的节点框
    • geom_text在节点上标注保留两位小数的均值

方案2:用柱状图替代数值(理想效果)

将分组节点替换为对应均值高度的柱状条,更直观展示数值大小:

ggplot(fit,
       aes(y = proportion, axis1 = K, axis2 = A, axis3 = Q, axis4 = defense)) +
  geom_alluvium(aes(fill = defense), width = 1/12) +
  # 用柱状条替换传统节点
  geom_col(stat = "stratum", aes(fill = defense), width = 1/12) +
  geom_text(stat = "stratum", aes(label = round(proportion, 2)), vjust = -0.5) +
  scale_x_discrete(limits = c("K", "A", "Q", "Defense"), expand = c(0.05, 0.05)) +
  scale_fill_brewer(type = "qual", palette = "Set1") +
  labs(title = "K-A-Q-Defense 流向图(柱状图展示均值)",
       x = "分组维度", y = "均值比例") +
  theme_minimal()
  • 这里用geom_col替代geom_stratum,让节点变成对应均值高度的柱状条,同时将数值标注在柱状条上方(vjust = -0.5调整位置)

额外优化建议

  • 若要展示误差棒(你的fit数据框包含se和ci列),可在柱状图方案中添加:
# 放在geom_col之后
geom_errorbar(stat = "stratum", aes(ymin = proportion - se, ymax = proportion + se),
              width = 0.1)
  • 可调整width参数改变流向带和柱状条的宽度,适配视觉需求
  • 自定义颜色方案可替换scale_fill_brewer,例如:
scale_fill_manual(values = c("HD" = "#2E86AB", "MD" = "#F24236"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:25:06