如何在Plotly Sankey图中固定单轴节点坐标,让另一轴自动布局?
解决Plotly Sankey图仅固定单轴(x轴)节点坐标的方法
核心思路
Plotly的Sankey布局逻辑是:只要节点的x或y包含NA值,就会完全触发自动布局,忽略所有自定义坐标设置。所以要实现只固定x坐标,得先让Plotly自动算出合理的y坐标,再手动替换x为我们需要的值,保留自动生成的y坐标即可。
具体步骤及代码示例
假设我们有如下节点和链接数据:
library(plotly) # 构造示例数据 nodes <- data.frame( label = c("A", "B", "C", "D", "E", "F") ) links <- data.frame( source = c(0, 0, 1, 1, 2, 3), target = c(2, 3, 2, 4, 5, 5), value = c(2, 3, 1, 4, 5, 2) )
步骤1:生成临时Sankey图,提取自动布局的节点坐标
先绘制一个无自定义坐标的Sankey图,从图对象里提取自动计算的节点x、y坐标:
# 生成临时图,获取自动布局的节点位置 temp_sankey <- plot_ly( type = "sankey", node = list(label = nodes$label), link = list( source = links$source, target = links$target, value = links$value ) ) # 提取自动计算的节点坐标 node_layout <- temp_sankey$x$data[[1]]$node auto_x <- node_layout$x auto_y <- node_layout$y
步骤2:替换x坐标为自定义值,保留自动y坐标
比如我们想把前两个节点固定在x=0,中间两个在x=0.5,最后两个在x=1:
# 自定义x坐标 custom_x <- c(0, 0, 0.5, 0.5, 1, 1) # 替换x,保留自动生成的y modified_node <- list( label = nodes$label, x = custom_x, y = auto_y, pad = 15, # 保持节点间距 thickness = 20 )
步骤3:用修改后的节点数据绘制最终Sankey图
# 绘制最终图 final_sankey <- plot_ly( type = "sankey", node = modified_node, link = list( source = links$source, target = links$target, value = links$value ) ) final_sankey
补充说明
- 如果仅需要部分节点固定x,其他节点自动分配x,只需在
custom_x里给对应位置设置目标值,其余保留auto_x的原始值即可 - 若要固定y坐标、让x自动布局,逻辑完全一致:先提取自动x坐标,替换为自定义y坐标即可
内容的提问来源于stack exchange,提问作者Moritz Schwarz
相关产品推荐
相关产品推荐

