问题
I am trying to get the nodes/edges data from my visNetwork graph. I am using the example code, but it is not working. I am trying to do this with Shiny. My goal is to get the nodes and edges data from the network and then display it in a table. I will greatly appreciate any help that I can get. Thanks,
Here is my code:
require(shiny)
require(visNetwork)
server <- function(input, output) {
output$network_proxy_nodes <- renderVisNetwork({
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges) %>% visNodes(color = "green")
})
output$edges_data_from_shiny <- renderPrint({
if(!is.null(input$network_proxy_get_edges)){
input$network_proxy_get_edges
}
})
observe({
input$getEdges
visNetworkProxy("network_proxy_get") %>%
visGetEdges()
})
output$nodes_data_from_shiny <- renderPrint({
if(!is.null(input$network_proxy_get_nodes)){
input$network_proxy_get_nodes
}
})
observe({
input$getNodes
visNetworkProxy("network_proxy_get") %>%
visGetNodes()
})
}
ui <- fluidPage(
visNetworkOutput("network_proxy_nodes", height = "100%"),
verbatimTextOutput("edges_data_from_shiny "),
verbatimTextOutput("nodes_data_from_shiny"),
actionButton("getNodes", "Nodes"),
actionButton("getEdges", "Edges")
)
shinyApp(ui = ui, server = server)
回答1:
The main problem with the code is that the name of the network output$network_proxy_nodes
was not the same everywhere.
This is a working piece of code to get edge information and display it in plain text, and to get node information and display it as a DataTable:
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)
})
output$nodes_data_from_shiny <- renderDataTable({
if(!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
}
})
output$edges_data_from_shiny <- renderPrint({
if(!is.null(input$network_proxy_edges)){
input$network_proxy_edges
}
})
observeEvent(input$getNodes,{
visNetworkProxy("network_proxy") %>%
visGetNodes()
})
observeEvent(input$getEdges, {
visNetworkProxy("network_proxy") %>%
visGetEdges()
})
}
ui <- fluidPage(
visNetworkOutput("network_proxy", height = "400px"),
verbatimTextOutput("edges_data_from_shiny"),
dataTableOutput("nodes_data_from_shiny"),
actionButton("getEdges", "Edges"),
actionButton("getNodes", "Nodes")
)
shinyApp(ui = ui, server = server)
来源:https://stackoverflow.com/questions/39905061/get-node-and-edge-data-from-visnetwork-graph