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

基于ggplot2在R中为冲积图特定流设置差异化配色

用ggalluvial实现冲积图的自定义流配色

原alluvial包的函数对单个流的颜色控制能力有限,推荐改用基于ggplot2的ggalluvial包,它能精准定义每一条流的配色。以下是具体实现步骤:

步骤1:安装并加载依赖包

# 首次运行时安装包
install.packages(c("ggalluvial", "dplyr"))

# 加载包
library(ggalluvial)
library(dplyr)

步骤2:准备数据

沿用你提供的原始数据即可:

df <- data.frame(Variable = c("X1", "X2", "X3", "X4", "X5", "X6"),
                 Pearson1 = c(6, 3, 2, 5, 4, 1),
                 Spearman1 = c(6, 5, 1, 2, 3, 4),
                 Kendall1 = c(6, 5, 1, 2, 3, 4),
                 Pearson2 = c(6, 5, 1, 2, 3, 4),
                 Spearman2 = c(6, 5, 1, 2, 4, 3),
                 Kendall2 = c(6, 5, 1, 2, 3, 4))
df$freq <- 1

步骤3:绘制带自定义配色的冲积图

核心是通过case_when定义颜色规则,精准匹配需要改色的流:

ggplot(df,
       aes(y = freq, axis1 = Variable, axis2 = Pearson1, axis3 = Spearman1,
           axis4 = Kendall1, axis5 = Pearson2, axis6 = Spearman2, axis7 = Kendall2)) +
  # 绘制冲积流,自定义填充色
  geom_alluvium(aes(fill = case_when(
    # Variables到Pearson1的X1流:匹配X1对应的Variable和Pearson1值
    Variable == "X1" & Pearson1 == 6 ~ "blue",
    # Kendall1到Spearman2的X1流:匹配X1对应的Kendall1和Spearman2值
    Kendall1 == 6 & Spearman2 == 6 ~ "green",
    # X3的所有流:直接匹配Variable为X3的行
    Variable == "X3" ~ "orange",
    # 其余流保留红色
    TRUE ~ "red"
  )), width = 1/12) +
  # 绘制轴上的分组区块
  geom_stratum(width = 1/12, fill = "white", color = "black") +
  # 添加区块标签
  geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 3) +
  # 设置轴的名称与间距
  scale_x_discrete(limits = c("Variable", "Pearson1", "Spearman1", "Kendall1", "Pearson2", "Spearman2", "Kendall2"),
                   expand = c(0.05, 0.05)) +
  # 关闭颜色图例(按需保留)
  guides(fill = "none") +
  theme_minimal()

说明

  • 每条流对应数据框的一行,通过行内变量值的组合就能精准定位目标流,你可以根据实际需求调整case_when里的匹配逻辑。
  • 也可以提前在数据框中新增一列custom_color,手动给每行分配颜色,再在geom_alluvium的aes(fill = custom_color)中直接引用,适配更复杂的配色需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:15:28