R语言 绘制不同步骤相同的Sankey图动画帧

gmxoilav  于 2023-02-14  发布在  其他
关注(0)|答案(2)|浏览(133)

我有一个问题,当试图使用动画的sankey通过不同的帧。我得到的两个步骤相同的sankey,尽管有不同的值在 Dataframe 。
![2020年框架][1]][1][![2021年框架][2]][2]
重现错误的代码如下所示

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")

  # Combine the vectors into a dataframe
  df <- data.frame(output, input, value, year, color)

  all_et <- as.list(unique(c(df$input, df$output)))
  source <- as.list(match(as.list(df$input), all_et) - 1)
  target <- as.list(match(as.list(df$output), all_et) - 1)

  plot_ly(
    type = "sankey",
    orientation = "h",
    valuesuffix = "TWh",

    node = list(
      pad = 10,
      thickness = 20,
      group = 1,
      line = list(width = 0),
      label = all_et,
      color = 'lightgray'
    ),
    link = list(
      source = source,
      target = target,
      line = list(color = "black", width = 0.01),
      value = as.list(df$value),
      color = as.list(df$color) #, # needs further development by plot_ly: waiting for new release js 2020.04.29
    ),
    frame = ~df$year
  )

你知道怎么解决这个问题吗?
谢谢[1]:https://i.stack.imgur.com/CIiQv.png [2]:https://i.stack.imgur.com/LNnfL.png

noj0wjuj

noj0wjuj1#

链接应该是从索引0开始的源和目标的数字表示(即“A”= 0,“B”= 1等)。
以下是满足这些要求的代码改编:

output <- c(0, 1, 2, 3, 4)
input <- c(1, 1, 5, 4, 5)
value <- c(1, 2, 1, 3, 2)
year <- c(2020, 2020, 2021, 2021, 2021)
color <- c("red", "blue", "green", "yellow", "orange")

# Combine the vectors into a dataframe
df <- data.frame(output, input, value, year, color)

plot_ly(
  type = "sankey",
  orientation = "h",
  valuesuffix = "TWh",
  
  node = list(
    pad = 10,
    thickness = 20,
    group = 1,
    line = list(width = 0),
    label = c("A", "B", "C", "D", "E", "G"),
    color = 'lightgray'
  ),
  link = list(
    source = df$input,
    target = df$output,
    line = list(color = "black", width = 0.01),
    value = df$value,
    color = df$color
  ),
  frame = df$year
)
mwyxok5s

mwyxok5s2#

基于Julian Selke的答案,解决方案是将字符串输入转换为数字,并修改如下代码

output <- c("A", "B", "C", "C", "B")
input <- c("B", "C", "A", "B", "A")
year <- c(2020, 2020, 2021, 2021, 2021)
color <- c("red", "blue", "green", "yellow", "orange")

# Combine the vectors into a dataframe
df <- data.frame(output, input, value, year, color)

  all_et <- unique(c(df$input, df$output))
  source <- match(as.list(df$input), all_et) - 1
  target <- match(as.list(df$output), all_et) - 1

plot_ly(
  type = "sankey",
  orientation = "h",
  valuesuffix = "TWh",

  node = list(
    pad = 10,
    thickness = 20,
    group = 1,
    line = list(width = 0),
    label = all_et,
    color = 'lightgray'
  ),
  link = list(
    source = source,
    target = target,
    line = list(color = "black", width = 0.01),
    value = df$value,
    color = df$color
  ),
  frame = df$year
)

相关问题