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

如何在维持节点顺序时让桑基图获取scale_fill_viridis全色阶

解决桑基图Factor节点下Viridis色阶范围受限问题

问题核心

将node列转为指定顺序的Factor后,使用scale_fill_viridis_d时颜色范围被压缩、丢失极端色值,同时需要保留节点的自定义展示顺序。

解决方案

无需在aes()中重复转换node为Factor,直接使用已定义的Factor列,并通过limits参数强制色阶覆盖所有Factor水平:

1. 保持原节点排序代码不变

df2$node <- factor(
  df2$node,
  levels = 
    c("Receiver + Mobile + Stationary", "Both + Mobile", ...) # 填入你的完整levels列表
)

2. 修改绘图代码

remotes::install_github("davidsjoberg/ggsankey")
library(ggsankey)
library(ggplot2)

p <- ggplot(df2, aes(
    x = x, 
    next_x = next_x, 
    node = node, 
    next_node = next_node, 
    fill = node,  # 直接使用已定义的factor列,无需二次转换
    label = node
  )) +
  geom_sankey(...)  # 保留你原有的geom_sankey参数
  scale_fill_viridis_d(
    begin = 1.0, 
    end = 0,
    limits = levels(df2$node)  # 强制色阶覆盖所有factor水平
  )

原理说明

  • 重复使用factor(node)会让ggplot自动根据绘图数据中实际出现的水平(而非你预先定义的Factor完整levels)生成颜色,导致色阶被压缩。直接使用fill = node可保留Factor的原始顺序与水平定义。
  • limits = levels(df2$node)强制颜色刻度使用你自定义的所有Factor水平,确保Viridis色阶从黄色(begin=1.0)到深蓝色(end=0)完整覆盖所有节点,避免颜色区分度降低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:03:28