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

使用ggalluvial绘制桑基图:按班次变更类型拆解观测数据

使用ggalluvial绘制班次变更桑基图

数据预处理

基于你提供的数据集,先为每个班次标记变更类型,覆盖要求的四类场景,同时支持多特征变更的展示:

library(data.table)
library(ggalluvial)
library(dplyr)

# 复用原始数据构建代码
data <- data.table(
  "shiftid" = c(1,1,2,2,3,3,4,4,5,5,6,6), 
  "version" = c(1,2,1,2,1,2,1,2,1,2,1,2), 
  "employee" = c("A", "B", "C", "C", "D", "D", "E", "F", "G", "H", "I", NA),
  "starttime" = c(1,1,2,3,4,6,7,7,8,9,9,NA))

data_wide <- dcast(data, shiftid ~ version, value.var = c("employee", "starttime"))

data_wide[, `:=`(employee_change = fifelse(employee_1 != employee_2,1,0),
                 starttime_change = fifelse(starttime_1 != starttime_2,1,0))]

# 标记变更类型,区分单一变更与多变更场景
data_wide[, change_type := case_when(
  is.na(employee_2) ~ "已删除",
  employee_change == 0 & starttime_change == 0 ~ "无变更",
  employee_change == 1 & starttime_change == 0 ~ "仅员工变更",
  employee_change == 0 & starttime_change == 1 ~ "仅开始时间变更",
  employee_change == 1 & starttime_change == 1 ~ "员工+开始时间变更"
)]

# 构建桑基图所需的源-目标-计数格式
sankey_data <- data_wide[, .N, by = change_type] %>%
  mutate(source = "所有班次") %>%
  rename(target = change_type, value = N) %>%
  select(source, target, value)

绘制桑基图

使用ggalluvial生成桑基图,直观展示班次从初始节点到各类变更类型的流向,清晰体现多特征变更的情况:

ggplot(sankey_data,
       aes(y = value, axis1 = source, axis2 = target)) +
  # 绘制流向区块
  geom_alluvium(aes(fill = target), width = 1/12) +
  # 绘制节点分层块
  geom_stratum(width = 1/12, fill = "white", color = "black") +
  # 添加节点标签
  geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
  # 设置坐标轴范围与间距
  scale_x_discrete(limits = c("所有班次", "变更类型"), expand = c(0.05, 0.05)) +
  # 设置填充配色
  scale_fill_brewer(type = "qual", palette = "Set1") +
  # 设置标题与轴标签
  labs(title = "班次变更类型拆解",
       x = "", y = "班次数量") +
  theme_minimal()

结果说明

  • 初始节点为所有班次(共6个,含5个有效班次+1个已删除班次)
  • 变更类型中单独列出了多特征变更类别,明确展示同时存在员工和开始时间变更的班次
  • 各类别数量与数据集完全匹配:无变更1个、已删除1个、仅开始时间变更2个、仅员工变更2个、员工+开始时间变更1个

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:10:37