Search code examples
rshinyvisnetwork

Deselect edges programmatically in Shiny in visNetwork


I want to deselect edges in a visNetwork network in Shiny. visSetSelection should work, but it doesn't: if I select an edge manually, then press the button, the edge remains selected. I don't know of any other way to do it. This https://github.com/almende/vis/issues/1670 suggests using visSelectEdges and setting the id to NULL but this also has no effect. Any ideas?

require(shiny)
require(visNetwork)

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

    visNetwork(nodes, edges)
  })

  observeEvent("deselect",{
  visNetworkProxy("network") %>%
    visSetSelection(edgesId = NULL,unselectAll = T) 


})
}

ui <- fluidPage(
  visNetworkOutput("network"),
  actionButton("deselect","Deselect")
)

shinyApp(ui = ui, server = server)

Solution

  • You can use visUnselectAll (see here). Also, you need to replace "deselect" by input$deselect in the condition of observeEvent.

    require(shiny)
    require(visNetwork)
    
    server <- function(input, output) {
      output$network <- renderVisNetwork({
        # minimal example
        nodes <- data.frame(id = 1:3)
        edges <- data.frame(from = c(1,2), to = c(1,3))
    
        visNetwork(nodes, edges)
      })
    
      observeEvent(input$deselect, {
        visNetworkProxy("network") %>%
          visUnselectAll()
    
      })
    }
    
    ui <- fluidPage(
      visNetworkOutput("network"),
      actionButton("deselect","Deselect")
    )
    
    shinyApp(ui = ui, server = server)