问题
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.
回答1:
Differents points :
- your javascript event
click
is wrong. Don't know aboutcurrent_node_id
and must be call in shiny withinput$click
and notclick$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)
来源:https://stackoverflow.com/questions/39916465/click-events-for-visnetwork-with-shiny