假设我将使用plotly绘制桑基图:
library(plotly)
library(dplyr)
input <- tibble(label = c("A1", "A2", "B1", "B2", "C1", "C2"),
color = c("blue", "blue", "red", "blue", "blue", "blue"),
source = c(0,1,0,2,3,0),
target = c(2,3,3,4,4,5),
x = c(0.1,0.3,0.5,0.7,1,0.9),
y = c(0.3,0.2,0.6,0.2,0.3,0.7),
value = c(8,4,2,8,4,2))
(fig <- plot_ly(
type = "sankey",
orientation = "h",
node = list(
label = input$label,
color = input$color,
pad = 150, # distance between nodes
x = input$x,
y = input$y
),
link = list(
source = input$source,
target = input$target,
value = input$value
)
))
在此示例中,我修复了
x
和 y
坐标。但假设我真的只关心两者之一(在本例中x
)并且想精心选择第二个坐标。
所以实际上我想做这样的事情:
input <- tibble(label = c("A1", "A2", "B1", "B2", "C1", "C2"),
color = c("blue", "blue", "red", "blue", "blue", "blue"),
source = c(0,1,0,2,3,0),
target = c(2,3,3,4,4,5),
x = c(0.1,0.3,0.5,0.7,1,0.9),
y = NA,
value = c(8,4,2,8,4,2))
然后 plotly 忽略 x 和 y 坐标 - 事实上,我得到的结果与删除节点列表中的 x 和 y 参数相同(请注意,例如 B2 的位置)。
所以它相当于:
(fig <- plot_ly(
type = "sankey",
orientation = "h",
node = list(
label = input$label,
color = input$color,
pad = 150 # distance between nodes
),
link = list(
source = input$source,
target = input$target,
value = input$value
)
))
关于如何修复其中一个坐标有什么想法吗?
创建绘图后,您可以使用
plotly_build
修改 y 坐标。这使您有机会为节点指定一个特定坐标,如下所示:
library(tibble)
library(plotly)
library(dplyr)
input <- tibble(label = c("A1", "A2", "B1", "B2", "C1", "C2"),
color = c("blue", "blue", "red", "blue", "blue", "blue"),
source = c(0,1,0,2,3,0),
target = c(2,3,3,4,4,5),
x = c(0.1,0.3,0.5,0.7,1,0.9),
y = NA,
value = c(8,4,2,8,4,2))
(fig <- plot_ly(
type = "sankey",
orientation = "h",
node = list(
label = input$label,
color = input$color,
pad = 150, # distance between nodes
x = input$x,
y = input$y
),
link = list(
source = input$source,
target = input$target,
value = input$value
)
))
your_fig <- plotly_build(fig)
your_fig$x$data[[1]]$node$y = c(NA, NA, NA, 1, NA, NA, NA)
your_fig
创建于 2023-11-14,使用 reprex v2.0.2
如您所见,节点 B2 现在具有不同的位置。