ashleych
ashleych

Reputation: 1054

How to not display values in the nodes or the links in SankeyDiagram using networkD3 in R

In the sankeydiagram example below, is there anyway to hide the "Values" being shown in the diagram while hovering - both on the Nodes as well as the Links. Im basically using the sankey chart to show a stylised flow diagram, and I would like the Values not be shown to the user at all

URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata/energy.json')
energy <- jsonlite::fromJSON(URL)

sankeyNetwork(Links = energy$links, Nodes = energy$nodes, Source = 'source',
              Target = 'target', Value = 'value', NodeID = 'name',
              units = 'TWh', fontSize = 12, nodeWidth = 30)

To be clear, in the screenshot below,I would still like to see the Wind-Electricitygrid, but would like 289KWH not be displayedenter image description here

Upvotes: 2

Views: 1086

Answers (1)

CJ Yetman
CJ Yetman

Reputation: 8848

You can generate any text you want to be displayed in the tooltips and add it to the htmlwidgets object, then use some custom JavaScript to set the tooltip text to it...

library(jsonlite)
library(networkD3)
library(htmlwidgets)

URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata/energy.json')
energy <- jsonlite::fromJSON(URL)

# generate the text you want to display
energy$links$name <-
  paste0(energy$nodes$name[energy$links$source + 1],
         " -> ", energy$nodes$name[energy$links$target + 1])

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

# add the names back into the links data because sankeyNetwork strips it out
sn$x$links$name <- energy$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

enter image description here

Upvotes: 3

Related Questions