How to keep a forceNetwork {networkD3} centered in a Shiny app?

旧城冷巷雨未停 提交于 2020-01-01 03:31:09

问题


While building a Shiny app that displays a forceNetwork graph, the network does not stay centered but moves out of view when one interactively changes the opacity.

My question is, how to change this behavior and keep the network nicely centered as it was initially?

A reproducible example:

ui.R:

library(shiny)
library(networkD3)

shinyUI(fluidPage( 

      titlePanel("ForceNetD3"), 

      sidebarLayout(
            sidebarPanel(
               sliderInput("opacity",
                      "Opacity",
                       min = 0.1,
                       max = 1,
                       value = 0.4)
      ),
      mainPanel(
            forceNetworkOutput(outputId = "net")
      )
)))

server.R:

library(shiny)
library(networkD3)

shinyServer(function(input, output) {

       # Load data
       data(MisLinks)
       data(MisNodes)      

       output$net <- renderForceNetwork(forceNetwork(
                          Links  = MisLinks, Nodes   = MisNodes,
                          Source = "source", Target  = "target",
                          Value  = "value",  NodeID  = "name",
                          Group  = "group",  opacity = input$opacity))
})

The behavior in pictures:

Annndd... it's gone:


回答1:


The problem is that the timer in d3.force() is running out, and it isn't "reheated" when new values are input. Without changes to networkD3, you can hack this to work by adding colourScale = JS('force.alpha(1); force.restart(); d3.scaleOrdinal(d3.schemeCategory20);') to your arguments in your forceNetwork() function. So you would have for server.R...

library(shiny)
library(networkD3)

shinyServer(function(input, output) {

       # Load data
       data(MisLinks)
       data(MisNodes)      

       output$net <- renderForceNetwork(forceNetwork(
                          Links  = MisLinks, Nodes   = MisNodes,
                          Source = "source", Target  = "target",
                          Value  = "value",  NodeID  = "name",
                          Group  = "group",  opacity = input$opacity,
                          colourScale = JS('force.alpha(1); force.restart(); d3.scaleOrdinal(d3.schemeCategory20);')))
})

UPDATE (2017.03.20)

This issue has been resolved in the most recent released version (0.4) of networkD3, and what the OP is asking for is the default behavior.



来源:https://stackoverflow.com/questions/42764760/how-to-keep-a-forcenetwork-networkd3-centered-in-a-shiny-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!