2

I've am using sankeyNetwork in the networkD3 package to create a visualisation

I would like to assign a name/ID to each edge, so that is appears in the tooltip. Can this be done with sankeyNetwork or any other function in the networkD3 package?

hjones85
  • 21
  • 3

1 Answers1

1

This is not technically supported, but you can achieve it like this...

library(networkD3)
library(htmlwidgets)

links <- data.frame(
  src = c(0, 0, 1, 2),
  target = c(2, 3, 2, 4),
  value = 1,
  name = c("first", "second", "third", "fourth")
)

nodes <- data.frame(name = c("one", "two", "three", "four", "five"))

# save the result of sankeyNetwork in an object
sn <- networkD3::sankeyNetwork(
  Links = links,
  Nodes = nodes,
  Source = 'src',
  Target = 'target',
  Value = 'value',
  NodeID = 'name'
)

# add the names back into the links data because sankeyNetwork strips it out
sn$x$links$name <- links$name

# add onRender JavaScript to set the title to the value of 'name' for each link
sn <- htmlwidgets::onRender(
  sn,
  '
  function(el, x) {
  d3.selectAll(".link").select("title foreignObject body pre")
  .text(function(d) { return d.name; });
  }
  '
)

# display the result
sn
CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
  • to add a question; is there a way to modify the style of the tooltips? – mzuba Oct 07 '19 at 10:37
  • Why not? Put whatever HTML you want in there – CJ Yetman Oct 07 '19 at 10:55
  • It seems to me that tooltips' HTML is not taken into account …https://www.dropbox.com/s/jhyw90vlgpi965f/style.png?dl=0 – mzuba Oct 07 '19 at 11:40
  • Basic HTML tooltips are very limited, and they are not necessarily consistent across browsers. If you want more than that you’ll have to use JavaScript and CSS to create pop up elements. – CJ Yetman Oct 07 '19 at 13:33
  • how can this be modified to show just the source and target names, with the values stripped out. for instance one -> two, two-> three etc, without the values being shown – ashleych Nov 10 '19 at 11:48
  • Open a new question with a minimal reproducible example – CJ Yetman Nov 10 '19 at 11:51