Search code examples
javascriptrd3.jshtmlwidgetsnetworkd3

Text shadow on networkD3 using HTMLWidget


I built a Sankey diagram in R using networkD3 package and I wanted to add text-shadow to the node labels. Actually, what I need is for the text to be in some way outlined because my original data is very complex and some of the text gets confused with the "lines" connecting the nodes. This was the approach I found on StackOverflow that should work fine, but if anyone has any other idea, I am open for new approaches.

I found a question whose implementation seems to be very similar to mine: Bold text in R using networkD3 package

But when I try the same approach, nothing happens.

A generic data would be:

library(networkD3)
URL <- "https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata/energy.json"
Energy <- jsonlite::fromJSON(URL)
sn <- sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              fontSize = 14, nodeWidth = 20, height = 900, width = 700, units = "px")

Like this, I tried on my own to use the onRender function of htmlwidgets but to no avail. As such, I adapted the code of the aforementioned topic but nothing changed in the generated widget:

library(htmlwidgets)
onRender(sn,
         '
  function(el) {
    d3.selectAll(".node text").attr("text-shadow", "1px 0 white, -1px 0 white, 0 1px white, 0-1px white")
  }
  '
)

Solution

  • To apply CSS styles, you need to use .style() instead of .attr()...

    htmlwidgets::onRender(sn, jsCode = '
      function(el) {
        d3.selectAll(".node text").style("text-shadow", "1px 0 white, -1px 0 white, 0 1px white, 0 -1px white")
      }
    ')
    

    enter image description here