Shiny & networkD3 responding to node click
htmlwidgets, javascript, networkd3, r, shiny
Solution
You could use `htmlwidgets`'s `onRender` function to attach an `onclick` event to the nodes like this...
library(shiny)
library(networkD3)
library(htmlwidgets)
URL <- "https://raw.githubusercontent.com/christophergandrud/networkD3/master/JSONdata/flare.json"
Flare <- jsonlite::fromJSON(URL, simplifyDataFrame = FALSE)
clickJS <- 'd3.selectAll(".node").on("click", function(d){ alert(d.data.name); })'
server <- function(input, output) {
output$simple <- renderDiagonalNetwork({
onRender(diagonalNetwork(List = Flare, fontSize = 10, opacity = 0.9), clickJS)
})
}
ui <- fluidPage(
diagonalNetworkOutput("simple"),
tags$script(clickJS)
)
shinyApp(ui = ui, server = server)
Problem
I am trying to use `networkD3` and shiny to visualize some data. I would like to have an action happen when a node in a graph is clicked. I am using the `diagonalNetwork` function as shown in the code below. The `forceNetwork` function has an option to make a `clickaction` to respond when a node is clicked. However, I cannot find a similar option for the `diagonalNetwork` function. Is there another way to implement this? ``` #### Load necessary packages and data #### library(shiny) library(networkD3) data(MisLinks) data(MisNodes) hc <- hclust(dist(USArrests), "ave") URL <- paste0( "https://cdn.rawgit.com/christophergandrud/networkD3/", "master/JSONdata//flare.json") ## Convert to list format Flare <- jsonlite::fromJSON(URL, simplifyDataFrame = FALSE) #### Server #### server <- function(input, output) { output$simple <- renderDiagonalNetwork({ diagonalNetwork(List = Flare, fontSize = 10, opacity = 0.9) }) output$force <- renderForceNetwork({ forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source", Target = "target", Value = "value", NodeID = "name", Group = "group", opacity = input$opacity) }) ## #dendroNetwork(hc, height = 600) # # dendroNetwork(hc, height = 500, width = 800, fontSize = 10, # linkColour = "#ccc", nodeColour = "#fff", nodeStroke = "steelblue", # textColour = "#111", textOpacity = 0.9, textRotate = NULL, # opacity = 0.9, margins = NULL, linkType = c("elbow", "diagonal"), # treeOrientation = c("horizontal", "vertical"), zoom = FALSE) } #### UI #### ui <- shinyUI(fluidPage( titlePanel("Shiny networkD3 "), sidebarLayout( sidebarPanel( sliderInput("opacity", "Opacity (not for Sankey)", 0.6, min = 0.1, max = 1, step = .1) ), mainPanel( tabsetPanel( tabPanel("Simple Network", diagonalNetworkOutput("simple")), tabPanel("Force Network", forceNetworkOutput("force")) ) ) ) )) #### Run #### shinyApp(ui = ui, server = server) ```