Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click events for VisNetwork with Shiny

Tags:

graph

r

vis.js

I have built my network with the visNetwork package in Shiny. I would like to click on a node and then display the information about the node from a dataframe. I have been able to do this for scatterplots with the click and nearpoint functions, such as the ones in the Shiny example shown here: http://shiny.rstudio.com/gallery/plot-interaction-selecting-points.html.

For my network, I have tried:

server <- function(input, output) {
output$network <- renderVisNetwork({
visNetwork(my.nodes, my.edges, 
           height = "100%", width = "100%",
           main = "") %>%
visEvents(hoverNode = "function(nodes){
            Shiny.onInputChange('current_node_id',nodes);
            ;}",
            click = "function(){
            Shiny.onInputChange('click',{node: current_node_id});
            ;}"
  )
})

output$shiny_return <- renderPrint({
if(!is.null(input$current_node_id)){
nearPoints(node.data,click$node, addDist = TRUE )    
}
})

ui <- fluidPage(
visNetworkOutput("network"), 
verbatimTextOutput("shiny_return")  
)

But, I get an error saying "click object not found"

Thank you for your help.

like image 878
AquieJo Avatar asked Mar 10 '23 23:03

AquieJo


1 Answers

Differents points :

  • your javascript event click is wrong. Don't know about current_node_id and must be call in shiny with input$click and not click$node
  • nearPoints is only for plotOuput. Can't use with javascript / htmlwidgets functions.

To enabled this kind of function with visNetwork, I've just add a new function visNearestNodes in the latest dev vervion. This is a simple example :

# install dev version
devtools::install_github("datastorm-open/visNetwork")

require(visNetwork)
require(shiny)

nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
                    group = sample(LETTERS[1:3], 15, replace = TRUE))

edges <- data.frame(from = trunc(runif(15)*(15-1))+1,
                    to = trunc(runif(15)*(15-1))+1)

server <- function(input, output, session) {
  output$network <- renderVisNetwork({
    visNetwork(nodes, edges, 
               height = "100%", width = "100%",
               main = "") %>%
      visEvents(click = "function(nodes){
                  Shiny.onInputChange('click', nodes.nodes[0]);
                  ;}"
      )
  })

  output$shiny_return <- renderPrint({
    visNetworkProxy("network") %>%
      visNearestNodes(target = input$click)
  })
}

ui <- fluidPage(
  visNetworkOutput("network"), 
  verbatimTextOutput("shiny_return")  
)

shiny::shinyApp(ui = ui, server = server)
like image 152
bthieurmel Avatar answered Mar 24 '23 07:03

bthieurmel