首页 > 解决方案 > R plotly 带注释列的桑基图

问题描述

我正在尝试创建一个带注释的桑基图。我希望最终版本与此手动注释图的线条一致:

在此处输入图像描述

获取桑基图的简单部分:

sankey_diagram <- plot_ly(
    type = "sankey",
    orientation = "h",

    node = list(
      label = c("Node_A_1", "Node_A_2", "Node_B_2", "Node_B_3", "Node_C_1", "Node_C_2"),
      color = c("blue", "blue", "blue", "blue", "blue", "blue"),
      pad = 15,
      thickness = 35,
      line = list(
        color = "black",
        width = 0.5
      )
    ),

    link = list(
      source = c(0,1,0,2,3,3),
      target = c(2,3,3,4,4,5),
      value =  c(8,4,2,8,4,2)
    )
  ) %>% 
  layout(
    font = list(
      size = 15
    )
)

起初我想如果我想获得带注释的“列”,我应该转向 plotly 文档的注释部分。注释的问题在于它们在空间上仅限于(至少我认为如此)图形的区域。这是基于注释的方法中的代码:

# properties that hide the axes
ax <- list(
  title = "",
  zeroline = FALSE,
  showline = FALSE,
  showticklabels = FALSE,
  showgrid = FALSE
)

sankey_diagram %>%
   add_annotations(
    x=-1,
    y=-5,
    xref = "x",
    yref = "y",
    text = "Column A",
    xanchor = 'right',
    showarrow = F
  ) %>% 
  add_annotations(
    x=0,
    y=-5,
    xref = "x",
    yref = "y",
    text = "Column B",
    xanchor = 'right',
    showarrow = F
  ) %>%
  add_annotations(
    x=1,
    y=-5,
    xref = "x",
    yref = "y",
    text = "Column C",
    xanchor = 'right',
    showarrow = F
  ) %>%  add_annotations(
    x=1,
    y=1,
    xref = "x",
    yref = "y",
    text = "", 
    xanchor = 'right',
    showarrow = F
  ) %>%
  layout(xaxis = ax, yaxis = ax)

问题是注释位于图表的底部,但不在图表下方。

第二种方法基于子图。我创建了两个子图 - 第一个是 Sankey,另一个是空的,除了注释 - 并将它们放在一行中:

columns_plot <- plot_ly() %>% add_annotations(
    x=-1,
    y=-5,
    xref = "x",
    yref = "y",
    text = "Column A",
    xanchor = 'right',
    showarrow = F
  ) %>% 
  add_annotations(
    x=0,
    y=-5,
    xref = "x",
    yref = "y",
    text = "Column B",
    xanchor = 'right',
    showarrow = F
  ) %>%
  add_annotations(
    x=1,
    y=-5,
    xref = "x",
    yref = "y",
    text = "Column C",
    xanchor = 'right',
    showarrow = F
  ) %>%  add_annotations(
    x=1,
    y=1,
    xref = "x",
    yref = "y",
    text = "", 
    xanchor = 'right',
    showarrow = F
  ) %>%
  layout(xaxis = ax, yaxis = ax)

p <- subplot(sankey_diagram, columns_plot, nrows = 2, shareX = TRUE, margin = 0.1)
p %>%
  layout(xaxis = ax, yaxis = ax)

出于某种奇怪的原因,巧妙地将columns_plot. sankey_diagram我怀疑第二种方法是正确的,但我仍然无法得到这个问题第一段中描述的结果。

标签: rplotlysubplotsankey-diagram

解决方案


推荐阅读