1

Using sankeyNetwork() in package , I want to customize the resulting diagram a little bit. The reproducible code is as following:

library(networkD3)

links <- data.frame(source = c(0, 0, 0, 0, 0, 2, 2, 3, 3), target = c(1, 2, 3, 4, 5, 6, 7, 6, 7), value = c(70, 56.4, 48.7, 0.9, 338.8, 50.8, 5.6, 47.3, 1.4))
nodes <- data.frame(name = c("Cu in obsolete TVs", "Illegal export", " Domestic recycling", "Open burning", "Dumping landfill", "Reuse", "Material recovery", "Material loss"))

sankeyNetwork(Links=links, Nodes=nodes, Source='source', Target='target',
          Value='value', NodeID='name', fontSize=16, sinksRight = FALSE)

I want to customize the resulting graph in the following ways:

  1. I want to move the label "Cu in obsolete TVs" to the left of the box for its corresponding node.

  2. I want to double the width of the box for Reuse.

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56

1 Answers1

1

The customizations you want are not possible using the built-in options of networkD3, but you can achieve them by using onRender() to run custom JavaScript when it loads. For example (also increased the right margin in the sankeyNetwork() function so the left justified label is not cut off):

library(networkD3)
library(htmlwidgets)

links <- data.frame(source = c(0, 0, 0, 0, 0, 2, 2, 3, 3), target = c(1, 2, 3, 4, 5, 6, 7, 6, 7), value = c(70, 56.4, 48.7, 0.9, 338.8, 50.8, 5.6, 47.3, 1.4))
nodes <- data.frame(name = c("Cu in obsolete TVs", "Illegal export", " Domestic recycling", "Open burning", "Dumping landfill", "Reuse", "Material recovery", "Material loss"))
sn <- sankeyNetwork(Links=links, Nodes=nodes, Source='source', Target='target',
              Value='value', NodeID='name', fontSize=16, sinksRight = FALSE, 
              margin = list(right = 150))

onRender(sn,
  '
  function(el,x) {
    d3.select(el)
      .selectAll(".node text")
      .filter(function(d) { return d.name == "Cu in obsolete TVs"; })
      .attr("x", x.options.nodeWidth - 16)
      .attr("text-anchor", "end");

    d3
      .selectAll("rect")
      .filter(function (d, i) { return i === 5;})
      .attr("width", x.options.nodeWidth * 2);
  }
  '
)

enter image description here

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
  • Thank you so much CJ Yetman. Also for your previous answer in another post, I found that it is not possible to adjust the vertical distance of node. I have another question concerning this diagram. Can we put values for each link into the graph? – user3045597 Sep 05 '18 at 06:16
  • you'd have to be more specific about what you mean by "put values"... the value is already included in the tooltip on each link... and better to ask in a new question to make it more easily seen/used by other users – CJ Yetman Sep 06 '18 at 14:24
  • 1
    I have opened a new question as you suggested at https://stackoverflow.com/questions/52226342/refine-sankey-diagram-with-sankeynetwork. Thank you so much. – user3045597 Sep 07 '18 at 16:19