5
require(shiny)
require(visNetwork)

server <- function(input, output) {

  output$network <- renderVisNetwork({
    nodes <- data.frame(id = 1:3)
    edges <- data.frame(from = c(1,2), to = c(1,3))

    visNetwork(nodes, edges) %>% visNodes(color = "green")
  })

  output$test <- renderPrint({
    input$network_positions
  })
  observe({
    input$goButton
    visNetworkProxy("network") %>%
      visGetPositions()
  })

}

ui <- fluidPage(
  fluidRow(
    column(10,visNetworkOutput("network", height = "100%"),
           verbatimTextOutput("test")),
    column(2, actionButton("goButton", "Go!"))
  )

)

shinyApp(ui = ui, server = server)

So visGetPositions only works in shiny. After you press Go, it calculates and prints out positions of each node. How do I extract it into R matrix so I can use it as coordinates?

Rorschach
  • 31,301
  • 5
  • 78
  • 129
James
  • 53
  • 3

1 Answers1

3

One possibility would be storing the coordinates in a reactiveValues, binding them together with rbind. For example, replacing your observer with the following,

vals <- reactiveValues(coords=NULL)
observeEvent(input$goButton, {
  visNetworkProxy("network") %>% visGetPositions()
  vals$coords <- if (!is.null(input$network_positions)) 
                   do.call(rbind, input$network_positions)
})

It checks for NULL so the do.call doesn't error. Then, the output$test changes to the following in order to check the result

output$test <- renderPrint( vals$coords )

update

A possible way to have the positions update without the button using invalidateLater:

output$test <- renderPrint( vals$coords )
vals <- reactiveValues(coords=NULL)
observe({
  invalidateLater(1000)
  visNetworkProxy("network") %>% visGetPositions()
  vals$coords <- if (!is.null(input$network_positions)) 
                   do.call(rbind, input$network_positions)
})
Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Hi, is there any automatic way the positions could be defined ? I have [SO question here](https://stackoverflow.com/questions/65583493/vis-network-define-node-location?noredirect=1#comment115959013_65583493). Can you please have a look and appreciate any inputs. – user5249203 Jan 06 '21 at 07:54