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

Plotly Sankey图动画帧异常:不同步骤显示相同图表求助

问题原因

你当前的代码把所有年份的链接数据(source、target、value)一次性传给了link参数,仅通过frame=~df$year无法实现按年份筛选链接——Plotly Sankey的动画需要为每个帧单独定义对应的链接集合,否则所有帧都会显示全部链接,导致视觉上无差异。

解决方法

按年份拆分数据,为每个年份生成独立的链接参数,再通过frames参数定义各帧内容,同时保持全局节点集合一致以保证布局稳定:

output <- c("A", "B", "C", "D", "E")
input <- c("B", "B", "G", "E", "G")
value <- c(1, 2, 1, 3, 2)
year <- c(2020, 2020, 2021, 2021, 2021)
color <- c("red", "blue", "green", "yellow", "orange")

df <- data.frame(output, input, value, year, color)

# 全局节点集合(确保所有帧节点一致)
all_et <- unique(c(df$input, df$output))

# 按年份分组处理数据
year_groups <- split(df, df$year)

# 构建每个帧的内容
frames <- lapply(names(year_groups), function(y) {
  group_df <- year_groups[[y]]
  source <- match(group_df$input, all_et) - 1
  target <- match(group_df$output, all_et) - 1
  
  list(
    name = y,
    data = list(list(
      type = "sankey",
      link = list(
        source = source,
        target = target,
        value = group_df$value,
        color = group_df$color,
        line = list(color = "black", width = 0.01)
      )
    ))
  )
})

# 初始图使用第一个年份的数据
initial_df <- year_groups[[1]]
initial_source <- match(initial_df$input, all_et) - 1
initial_target <- match(initial_df$output, all_et) - 1

plot_ly(
  type = "sankey",
  orientation = "h",
  valuesuffix = "TWh",
  node = list(
    pad = 10,
    thickness = 20,
    line = list(width = 0),
    label = all_et,
    color = 'lightgray'
  ),
  link = list(
    source = initial_source,
    target = initial_target,
    value = initial_df$value,
    color = initial_df$color,
    line = list(color = "black", width = 0.01)
  ),
  frames = frames
) %>% 
  animation_opts(
    frame = 1000,  # 帧切换时长(毫秒)
    transition = 500,  # 过渡时长
    redraw = TRUE
  ) %>%
  animation_slider(
    currentvalue = list(prefix = "年份: ")
  )
关键修改点
  • 用split()按年份拆分数据,确保每个帧只包含对应年份的链接
  • 基于全局节点集合all_et计算source/target索引,避免不同帧节点顺序混乱
  • 通过frames参数明确每个帧的链接数据,替代原代码中无效的frame=~df$year
  • 添加动画控制选项(animation_opts和animation_slider)优化交互体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:05:43