问题
I am having a hard time working with networkd3 package in Shiny. I have plotted a graph and would like to extract node information back to shiny in a reactive manner to visualize more information concerning a certain node. E.g star graph with center node "Father" and other "Son1"..."SonN". Upon clicking on the Son node I would like to be able to access the "Son1" name in shiny to extract information from a data frame within shiny and visualize additional information (e.g job, age and so on). I was able to use clickAction to for example show a message on the screen:
forceNetwork(....., clickAction= 'alert(d.name)')
but I do not know how to get this d.name value back into shiny, so I can use it further and that I do not get an error when starting to run shiny, since the d.name does not exist from the begning (maybe observe function here?) I basically need an equivalent of DT package input$table_rows_selected
.
回答1:
Here's a really rough, but working, example of a networkD3
forceNetwork
plot returning a value on click (using clickAction = 'Shiny.onInputChange("id", d.name)'
), which is then used to display a data frame with that name.
library(shiny)
library(networkD3)
links <- read.table(header = T, text = '
source target value
0 1 1
0 2 1
')
nodes <- read.table(header = T, text = '
name group
dad 1
son1 1
son2 1
')
son1 <- read.table(text = '
name John
age 18
')
son2 <- read.table(text = '
name Mark
age 14
')
ui <- shinyUI(fluidPage(
fluidRow(
column(4, forceNetworkOutput("force")),
column(4, DT::dataTableOutput("table"))
)
))
server <- shinyServer(function(input, output) {
output$force <- renderForceNetwork({
forceNetwork(Links = links, Nodes = nodes, Source = "source",
Target = "target", Value = "value", NodeID = "name",
Group = "group", opacity = 1, opacityNoHover = 1,
clickAction = 'Shiny.onInputChange("id", d.name)')
})
output$table <- DT::renderDataTable(DT::datatable(get(input$id)))
})
shinyApp(ui = ui, server = server)
来源:https://stackoverflow.com/questions/45217609/extracting-node-information-from-networkd3-to-a-reactive-variable-in-shiny