Search code examples
rgraphshinyshinydashboard

Search bar with VisNetwork Graph in Shiny


I have built a network graph with VisNetwork and Shiny. I am very pleased with the results. What I would like to do is use a search bar (for example: http://projects.flowingdata.com/tut/interactive_network_demo/) to search the nodes in my data.

I am using shinydashboard. So I tried to use the "sidebarSearchForm". However, when I run the app and try to use the search form, nothing is returned.

Here is my code for the ui:

ui <- dashboardPage(skin = "black",
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Network", tabName = "network", icon = icon("dashboard")),
      sidebarSearchForm(textId = "searchText", buttonId = "searchButton", label = "Search...")
   )
  ),
  dashboardBody(
    box(
      title = "Network",  status = "warning", solidHeader = TRUE, collapsible = TRUE,
      visNetworkOutput("network_proxy", height = 700)  
    )
  )
)#end ui

Here is the code for the server;

server <- function(input, output) {
  output$network_proxy <- renderVisNetwork({
    visNetwork(my.nodes, my.edges, height = "100%")
  })
  output$searchString <- renderText({
    if (input$searchButton == 0)
      return()
    isolate({input$searchString})
  })
} #end server

Solution

  • You can do this using visNetworkProxy and visSelectNodes for example, like this with a simple grepl :

    nodes <- data.frame(id = 1:3, label = c("A", "B", "A"))
    edges <- data.frame(from = c(1,2), to = c(1,3))
    
    require(visNetwork)
    require(shiny)
    require(shinydashboard)
    ui <- dashboardPage(skin = "black",
                        dashboardHeader(),
                        dashboardSidebar(
                          sidebarMenu(
                            menuItem("Network", tabName = "network", icon = icon("dashboard")),
                            sidebarSearchForm(textId = "searchText", buttonId = "searchButton", label = "Search...")
                          )
                        ),
                        dashboardBody(
                          box(
                            title = "Network",  status = "warning", solidHeader = TRUE, collapsible = TRUE,
                            visNetworkOutput("network_proxy", height = 700)
                          )
                        )
    )
    
    
    server <- function(input, output, session) {
      output$network_proxy <- renderVisNetwork({
        visNetwork(nodes, edges, height = "100%")
      })
    
      observe({
        if(input$searchButton > 0){
          isolate({
            print(input$searchText)
            current_node <- nodes[grep(input$searchText, nodes$label), "id"]
            print(current_node)
            visNetworkProxy("network_proxy") %>% visSelectNodes(id  = current_node)
          })
        }
      })
    
    } #end server
    
    shiny::shinyApp(ui, server)