我有
nodes
和 links
数据框来绘制 sankey
图表,其中 plot_ly
中的 r
。
nodes <- data.frame(
name = c(
"st_con_rt/main-room", "st_con_rt/sub-room", "st_con_tr/direct",
"st_con_tr/terrace", "st_adsb/add", "st_adsb/sub", "st_th/hira",
"st_th/tsuma", "tr_adsb/add", "tr_adsb/sub", "st_sub_main_th/hira",
"st_sub_main_th/other", "st_sub_main_th/tsuma", "st_sub2_main_th/hira",
"st_sub2_main_th/other", "st_sub2_main_th/tsuma", "roo_com/2a",
"roo_com/1a+7", "roo_com/4a", "roo_com/2a+7", "roo_com/3b+7",
"roo_com/1b+7", "roo_com/7"
),
x = c(0.1, 0.1, 0.2, 0.2, 0.3, 0.3, 0.4, 0.4, 0.5, 0.5, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8)
)
links <- data.frame(
source = c(0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15),
target = c(2, 3, 2, 3, 4, 5, 6, 7, 4, 7, 9, 10, 12, 8, 10, 11, 13, 5, 10, 17, 17, 18, 19, 2, 21, 22, 17),
value = c(2, 3, 5, 1, 3, 2, 1, 1, 1, 3, 4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1)
)
我使用以下脚本绘制桑基图,假设节点将按照
node$x
从左到右对齐,即按st_con_rt
、st_con_tr
、st_adsb
、st_th
、tr_adsb
的顺序排列、 st_sub_main_th
、st_sub2_main_th
和 roo_com
。
plot_ly(type="sankey", orientation="h", arrangement="snap",
node = list(label=nodes$name, x=nodes$x, pad=10),
link = links
)
但是,输出图并不遵循脚本中指定的 x 位置。
例如,前缀为
st_th
的两个元素现在处于第三顺序,而其位置为第四。 tr_adsb
、st_sub_main_th
和 st_sub2_main_th
位于相同的第 5 个位置,有些位于第 6 个位置。
我想这可能是由于根据每个元素的出现情况自动对齐而发生的,因此我尝试了其他布局参数,例如
freeform
,但结果是相同的。
有什么方法可以根据需要固定节点的 x 轴吗?
根据我的经验,实现此功能的唯一方法是同时提供 y 坐标和 x 坐标。如果您使用对齐排列,您可以将 y 设置为固定数字,并且节点应垂直展开,直到它们不重叠。
我发现这相当不可靠,似乎如果单个 x 位置有太多节点,它仍然偶尔会将节点移动到应有位置的右侧。
请注意,您的示例代码不起作用,为数据框提供的行数对于链接和节点都是不正确的。下面带有固定数据框的内容可能会为您提供您正在寻找的内容。您可以稍微改变 y 位置来上下移动整个图形,但如果您将其设置得太接近 0 或 1,您可能会在画布外绘制节点。
nodes <- data.frame(
name = c(
"st_con_rt/main-room", "st_con_rt/sub-room", "st_con_tr/direct",
"st_con_tr/terrace", "st_adsb/add", "st_adsb/sub", "st_th/hira",
"st_th/tsuma", "tr_adsb/add", "tr_adsb/sub", "st_sub_main_th/hira",
"st_sub_main_th/other", "st_sub_main_th/tsuma", "st_sub2_main_th/hira",
"st_sub2_main_th/other", "st_sub2_main_th/tsuma", "roo_com/2a",
"roo_com/1a+7", "roo_com/4a", "roo_com/2a+7", "roo_com/3b+7",
"roo_com/1b+7"
),
x = c(0.1, 0.1, 0.2, 0.2, 0.3, 0.3, 0.4, 0.4, 0.5, 0.5, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8)
)
links <- data.frame(
source = c(0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15),
target = c(2, 3, 2, 3, 4, 5, 6, 7, 4, 7, 9, 10, 12, 8, 10, 11, 13, 5, 10, 17, 17, 18, 19, 2, 21, 22),
value = c(2, 3, 5, 1, 3, 2, 1, 1, 1, 3, 4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1)
)
plot_ly(type="sankey", orientation="h", arrangement="snap",
node = list(label=nodes$name, x=nodes$x, y=rep(0.4, length(nodes$x)), pad=10),
link = links
)
这一切都有点笨拙,但通过一些 y 值和填充的尝试,我通常可以让它按照我想要的方式工作。