R 中的 networkD3 -> 在 forceNetwork() 中设置初始缩放

networkD3 in R -> Set Initial Zoom in forceNetwork()

我正在处理一个大网络(1k + 节点,1M + 连接),我想设置自定义初始缩放,因为标准缩放只关注几个节点并且需要很多时间才能达到目标比例(在这里我可以看到整个网络)。

这是我的代码:

library(networkD3)

p <- forceNetwork(Links = links, 
                  Nodes = nodes, 
                  Source = 'source', 
                  Target = 'target', 
                  NodeID = 'name',
                  Group = 'group', 
                  Value = "value",
                  Nodesize = "size",
                  radiusCalculation = JS("d.nodesize"),
                  zoom = TRUE, 
                  arrows = FALSE,
                  linkWidth = JS("function(d){return d.value;}"),
                  linkDistance = JS("function(d){return d.value*10}"),
                  charge = gravity,
                  opacity = 0.95,
                  fontSize = 24,
                  linkColour = "#424242"
)

customJS <- 
  "function() { 
    d3.selectAll('.node text').style('fill', 'white').attr('stroke-width', '.1px').attr('stroke', '#3f3f3f');
    d3.select('body').style('background-color', '#15171a');
    simulation = this;
    simulation.stop();
    for (var i = 0; i < 300; ++i) simulation.tick();
    simulation.nodes().forEach( function(d,i) {
      d.cx = d.x;
      d.cy = d.y;
    });
    simulation.restart();
  }"


g <- htmlwidgets::onRender(p, customJS)
g

这是在渲染上设置比例值的最小化、可重现的示例...

library(networkD3)

p <- forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source",
            Target = "target", Value = "value", NodeID = "name",
            Group = "group", opacity = 0.4, zoom = TRUE)

customJS <- 
  'function(el) { 
     d3.select(el).select(".zoom-layer").attr("transform", "scale(0.3)")
  }'


htmlwidgets::onRender(p, customJS)