更新时间:2023-01-16 21:03:07
To display data of the node selected, you can adapt the example given in visNetwork Shiny webpage. In that example, hoverNode
option of visEvents
is used to get information of the hovered node.
To get the selected node id one can use:
visEvents(select = "function(nodes) {
Shiny.onInputChange('current_node_id', nodes.nodes);
;}")
This function sets the id of the node (nodes.nodes
) to input$current_node_id
. Then, you can use this information to display only the information corresponding to that node (by subsetting the data.frame).
Below, the example provided adapted to answer the question:
require(shiny)
require(visNetwork)
server <- function(input, output, session) {
nodes <- data.frame(id = 1:3,
name = c("first", "second", "third"),
extra = c("info1", "info2", "info3"))
edges <- data.frame(from = c(1,2), to = c(1,3), id = 1:2)
output$network_proxy <- renderVisNetwork({
visNetwork(nodes, edges) %>%
visEvents(select = "function(nodes) {
Shiny.onInputChange('current_node_id', nodes.nodes);
;}")
})
output$nodes_data_from_shiny <- renderDataTable( {
if (!is.null(input$current_node_id) && !is.null(input$network_proxy_nodes)) {
info <- data.frame(matrix(unlist(input$network_proxy_nodes),
ncol = dim(nodes)[1], byrow = T),
stringsAsFactors = FALSE)
colnames(info) <- colnames(nodes)
info[info$id == input$current_node_id, ]
}
})
observeEvent(input$current_node_id, {
visNetworkProxy("network_proxy") %>%
visGetNodes()
})
}
ui <- fluidPage(
visNetworkOutput("network_proxy", height = "400px"),
dataTableOutput("nodes_data_from_shiny"),
actionButton("getNodes", "Nodes")
)
shinyApp(ui = ui, server = server)