Home > Enterprise >  R forceNetwork - how do I keep the legend in the top left corner when zooming is enabled?
R forceNetwork - how do I keep the legend in the top left corner when zooming is enabled?

Time:04-06

Hoping there is a solution to this. I would like to enable the zoom options in the forceNetwork function of the networkD3 package, and force the legend to remain in the top left corner when zooming in and out. In the example below, if you zoom in and out the legend does not remain in the top left corner. I have a similar network in an R Shiny application using my own dataset. Does anyone know how to do this?

library(networkD3)

data(MisLinks)
data(MisNodes)

# Create graph
forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 1, zoom = T, bounded = F,legend = T)

CodePudding user response:

Here's a way to move all the legend elements to a different group than that zoom layer so they won't zoom with the rest...

library(networkD3)
library(htmlwidgets)

data(MisLinks)
data(MisNodes)

# Create graph
fn <- forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 1, zoom = T, bounded = F,legend = T)

htmlwidgets::onRender(fn, jsCode = '
  function (el, x) {
    d3.select("svg").append("g").attr("id", "legend-layer");
    var legend_layer = d3.select("#legend-layer");
    d3.selectAll(".legend")
      .each(function() { legend_layer.append(() => this); });
  }
')

enter image description here

  • Related