我正在尝试创建带注释的Sankey图。我希望最终版本能够遵循此手动注释图的思路:
获取Sankey图的简单部分:
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
的顶部。我怀疑第二种方法是正确的,但仍然无法获得此问题第一段中描述的结果。