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

如何为R语言sankey_ly生成的桑基图添加分类节点列标题?

解决桑基图添加分类节点列标题的问题

你用sfo包的sankey_ly生成的桑基图默认没有列标题,因为这个函数本身没提供直接设置该参数的选项,但可以借助它返回的plotly对象手动添加注释实现:

步骤1:保存桑基图对象,再添加列标题

修改后的完整代码如下:

library(dplyr)
library(sfo)
library(plotly)

# 数据预处理
sankey_data <- sfo_passengers %>% 
  filter(operating_airline == "United Airlines",
         activity_period >= 201901 & activity_period < 202001) %>%
  mutate(terminal = ifelse(terminal == "International", "international", terminal)) %>%
  group_by(operating_airline, activity_type_code, geo_summary, geo_region, terminal) %>%
  summarise(total = sum(passenger_count), .groups = "drop")

# 生成桑基图基础对象
p <- sankey_ly(sankey_data,
               cat_cols = c("operating_airline", "terminal","geo_summary", "geo_region", "activity_type_code"), 
               num_col = "total",
               title = "2019年旧金山机场美联航乘客分布桑基图")

# 给每一列节点添加标题
p %>%
  add_annotations(
    x = c(0, 1, 2, 3, 4),  # 对应cat_cols中5个分类的列位置(从左到右0到4)
    y = 1.05,               # 标题位置在图的上方区域
    text = c("航空公司", "航站楼", "地区汇总", "细分地区", "出行类型"),  # 自定义列标题,也可用原列名
    showarrow = FALSE,      # 隐藏箭头
    xref = "x",
    yref = "paper",
    font = list(size = 12)  # 设置标题字体大小
  )

关键说明

  • x参数的数值对应桑基图从左到右的列顺序,和cat_cols里的列顺序完全一致;
  • y = 1.05是把标题放在画布顶部(paper坐标下1是顶部,1.05超出一点避免和节点重叠);
  • text可以替换成你需要的标题文本,比如直接用原列名c("operating_airline", "terminal", "geo_summary", "geo_region", "activity_type_code")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:17:09