R 中的 networkD3 - 冻结 forceNetwork()

networkD3 in R - Freeze forceNetwork()

有什么方法可以在 {networkD3} 库中使用 forceNetwork() 冻结布局?

这占用了我很多时间,因为我的网络有很多节点。我只需要停止动画。我发现了一些东西 here,但没有解决我的问题。

这是我的部分代码:

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');
    d3.layout.force().tick();
    d3.layout.force().stop();
  }"


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() {
    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();
  }
'

htmlwidgets::onRender(p, customJS)

我也一直在研究 {networkD3} 的继任者,它可以轻松做到这一点(尽管默认情况下它使用 canvas 而不是 SVG,因此它可以处理更多的数据,即使使用动画)...

library(network.r2d3)
url <- "https://gist.githubusercontent.com/mbostock/ad70335eeef6d167bc36fd3c04378048/raw/df541a01e850c6073ece4516fcd74ea1bae080ab/miserables.json"
force_network(url, plot_static = TRUE)