Skip to content Skip to sidebar Skip to footer

Highlight All Connected Paths From Start To End Of A Sankey Diagram Using Networkd3

I would like to produce a Sankey-diagram using the networkD3 package in R that has the functionality as described in this question, and the 'highlight_node_links' function in the a

Solution 1:

When I run your code, I get the warning message...

Warning message:
It looks like Source/Targetis not zero-indexed. ThisisrequiredinJavaScript
 and so your plot may not render.

which tells you what the root of the problem is... your links and nodes data frames are not properly created.

You can easily resolve this by adding stringsAsFactors = FALSE as a parameter to the data.frame command that you use to create the links data frame.

Working example...

library(networkD3)
library(htmlwidgets)
library(dplyr)

links = data.frame(
  source = c("me",  "you", "she", "p1",  "p1",  "p2",  "p2"),
  target = c("p1",  "p2",  "p1",  "p2",  "b1",  "b1",  "b2"),
  weight = c(20, 10, 30, 40, 60, 50, 50),
  stringsAsFactors =FALSE
)
nodes <-
  data.frame(name = c(links$source, links$target) %>% unique())
links$IDsource= match(links$source, nodes$name) -1
links$IDtarget= match(links$target, nodes$name) -1

sn <- sankeyNetwork(
  Links= links,
  Nodes= nodes,
  Source="IDsource",
  Target="IDtarget",
  Value="weight",
  NodeID="name",
  sinksRight =TRUE
)

htmlwidgets::onRender(
  sn,
  '
        function(el, x) {
          var link = d3.selectAll(".link");
         var node = d3.selectAll(".node");
        node.on("mousedown.drag", null);
        node.on("click",highlight_node_links)}'
)

enter image description here

Post a Comment for "Highlight All Connected Paths From Start To End Of A Sankey Diagram Using Networkd3"