3

我希望在这个 sankey 图上实现 onClick,以便通过单击链接,我应该看到两个节点之间链接的详细信息。就像 plotly_click 函数

library(networkD3)
nodes = data.frame("name" = 
                 c("r1", # Node 0
                   "r2", # Node 1
                   "r3", # Node 2
                   "r4", # Node 3
                   "r5", # Node 4
                   "r6", # Node 5
                   "r7", # Node 6
                   "Blood Test", # Node 7
                   "Check Out", # Node 8
                   "Discuss Results", # Node 9
                   "MRI Scan", # Node 10
                   "Registration", # Node 11
                   "Triage and Assessment", # Node 12
                   "X-ray"))# Node 13
links = as.data.frame(matrix(c(
0, 11, 500, # Each row represents a link. The first number
1, 12, 500, # represents the node being conntected from. 
2, 7, 237, # the second number represents the node connected to.
3, 10, 236,
4, 13, 261,
5, 9, 495,
6, 8, 492),# The third number is the value of the node

byrow = TRUE, ncol = 3))
names(links) = c("source", "target", "value")
sankeyNetwork(Links = links, Nodes = nodes,
          Source = "source", Target = "target",
          Value = "value", NodeID = "name",
          fontSize= 12, nodeWidth = 30)

桑基斯内普

4

2 回答 2

2

htmlwidgets::onRender您可以使用函数添加点击事件。目前尚不清楚您想查看哪些详细信息,但是例如,当您单击链接时,它将在警报框中显示链接的值...

library(htmlwidgets)

sn <- sankeyNetwork(Links = links, Nodes = nodes,
              Source = "source", Target = "target",
              Value = "value", NodeID = "name",
              fontSize = 12, nodeWidth = 30)

clickJS <- 'd3.selectAll(".link").on("click", function(d){ alert(d.value); })'
htmlwidgets::onRender(sn, clickJS)
于 2017-10-25T10:32:52.467 回答
1

这是一个基于parset包的有趣解决方案:

devtools::install_github("timelyportfolio/parsetR")
library(parsetR) 

links$source <- as.character(factor(links$source, labels=nodes[1:7,1]))
links$target <- as.character(factor(links$target, labels=nodes[8:14,1]))

parset(links, dimensions = c('source', 'target'), 
       value = htmlwidgets::JS("function(d) {return d.value}"),  
       tension = 0.5)

在此处输入图像描述

于 2017-10-11T13:37:49.490 回答