R plotly - 未返回桑基图

R plotly - sankey chart not returned

我 运行 在 RStudio 的代码下面,想用 plotly 创建桑基图。代码运行没有错误。但未显示桑基图。这里有什么问题?

library("plotly")
a = read.csv('cleanSankey.csv', header=TRUE, sep=',')
node_names <- unique(c(as.character(a$source), as.character(a$target)))
nodes <- data.frame(name = node_names)
links <- data.frame(source = match(a$source, node_names) - 1,
                    target = match(a$target, node_names) - 1,
                    value = a$value)

nodes_with_position <- data.frame(
  "id" = names,
  "label" = node_names,
  "x" = c(0, 0.1, 0.2, 0.3,0.4,0.5,0.6,0.7),
  "y" = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7)
)

#Plot
plot_ly(type='sankey',
        orientation = "h",
        
        node = list(
          label = node_names,
          x = nodes_with_position$x,
          y = nodes_with_position$y,
          color = "grey",
          pad = 15,
          thinkness = 20,
          line = list(color = "grey", width = 0.5)),
 
         link = list(
           source = links$source,
           target = links$target,
           value = links$value))

这里是示例 csv 数据:

date,Data Center,Customer,companyID,source,target,value 6/1/2021,dcA,customer1,companyID1,step1:open_list_view,exit,1 6/1/2021,dcB,customer2,companyID2,step1:open_list_view,exit,1 6/1/2021,dcC,customer3,companyID3,step1:open_list_view,exit,1 6/2/2021,dcD,customer4,companyID4,step1:open_list_view,exit,2 6/2/2021,dcE,customer5,companyID5,step1:open_list_view,step2:switch_display_option,1

sankey 已绘制,但第二层的节点转到最后一层。如何固定节点位置?

您需要通过设置 arrangement 参数来定义节点位置,以停止 plotly 自动调整位置。

这需要一些技巧,因为您需要指定节点的坐标。您可以在此处找到更多详细信息:https://plotly.com/python/sankey-diagram/#define-node-position

代码

library(plotly)

a <- read.csv("~/cleanSankey.csv")

node_names <- unique(c(as.character(a$source), as.character(a$target)))

# added id column for clarity, but it's likely not needed
nodes <- data.frame(
  id = 0:(length(node_names)-1),
  name = node_names
)

links <- data.frame(
  source = match(a$source, node_names) - 1,
  target = match(a$target, node_names) - 1,
  value = a$value
)

# set the coordinates of the nodes
nodes$x <- c(0, 1, 0.5)
nodes$y <- c(0, 0.5, 1)

# plot - note the `arrangement="snap"` argument
plot_ly(
  type='sankey',
  orientation = "h",
  arrangement="snap", # can also change this to 'fixed'
  node = list(
    label = nodes$name,
    x = nodes$x,
    y = nodes$y,
    color = "grey",
    pad = 15,
    thinkness = 20,
    line = list(color = "grey", width = 0.5)
  ),
  link = list(
    source = links$source,
    target = links$target,
    value = links$value
  )
)

使用 arrangement="snap" 绘制输出: