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

如何将桑基图(Sankey)第二个节点的geom_text标签左移

解决ggplot2桑基图第二个节点文本移至左侧的方案

不管你用ggalluvial还是ggsankey(这两个是ggplot生态最常用的桑基图工具),核心思路都是根据节点的位置索引,针对性调整文本的对齐方式或偏移量,以下是具体实现:

前提说明

假设你的数据是典型的桑基图格式,这里用示例数据演示:

示例数据

library(tidyverse)
# 宽格式数据(适配ggalluvial)
df_wide <- tibble(
  第一节点 = rep(c("A", "B", "C"), each = 2),
  第二节点 = rep(c("X", "Y"), 3),
  流量 = c(10, 15, 8, 12, 5, 9)
)

# 长格式数据(适配ggsankey)
df_long <- df_wide %>%
  make_long(第一节点, 第二节点, 流量)

方案1:使用ggalluvial包

原代码默认文本在节点右侧,修改geom_text的hjust参数即可实现位置切换:

修改后代码

library(ggalluvial)

ggplot(df_wide, aes(y = 流量, axis1 = 第一节点, axis2 = 第二节点)) +
  geom_alluvium(aes(fill = 第一节点)) +
  geom_stratum() +
  # 核心:根据节点索引设置文本位置
  geom_text(
    stat = "stratum",
    aes(
      label = after_stat(stratum),
      # axis=2对应第二个节点,hjust=1.2让文本左对齐显示在节点左侧
      hjust = ifelse(after_stat(axis) == 2, 1.2, -0.2)
    )
  ) +
  # 必须扩大x轴空白,避免文本被截断
  scale_x_discrete(limits = c("第一节点", "第二节点"), expand = c(0.2, 0.2)) +
  theme_minimal()

关键逻辑

  • after_stat(axis)能获取当前文本所属的节点序号(axis1对应1,axis2对应2)
  • hjust=1.2表示文本右边缘对齐节点左边缘,自然显示在节点左侧;hjust=-0.2让第一个节点的文本保持在右侧
  • expand参数必须调整,给文本留出足够显示空间

方案2:使用ggsankey包

如果用ggsankey,调整geom_sankey_label的hjust参数即可:

修改后代码

library(ggsankey)

ggplot(df_long, aes(
  x = x, next_x = next_x,
  node = node, next_node = next_node,
  fill = node, label = node,
  value = 流量
)) +
  geom_sankey(flow.alpha = 0.6) +
  # 核心:x=2对应第二个节点,hjust=1让文本左对齐显示在左侧
  geom_sankey_label(hjust = ifelse(df_long$x == 2, 1, 0), fill = "white") +
  scale_x_discrete(expand = c(0.2, 0.2)) +
  theme_minimal()

注意事项

  • 如果你的节点数量更多,只需修改ifelse的判断条件(比如axis==3对应第三个节点)
  • 偏移量(hjust数值)可以根据你的图大小自行调整,确保文本不遮挡节点或流
  • 若文本仍被截断,进一步增大scale_x_discrete的expand参数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:30:22