0

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)
CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
AyeTown
  • 831
  • 1
  • 5
  • 20

1 Answers1

0

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

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
  • yeah this works well thanks! just curious... what exactly do "g" and "id" correspond to in the onRender function? thinking I can change these values for another network I have where the legend is based on border color instead. – AyeTown Apr 05 '22 at 19:45
  • `append("g")` adds a SVG group, which is a container for other elements, kinda like a HTML
    . "id" is an attribute that allows you to select an element in the DOM by id. Here, I created a new element and gave it the id "legend-layer". Then I selected all of the existing elements with the class "legend" and moved them into the new .
    – CJ Yetman Apr 05 '22 at 21:30