7

我正在尝试使用networkD3和闪亮来可视化一些数据。我希望在单击图表中的节点时发生动作。我正在使用diagonalNetwork如下代码所示的函数。

forceNetwork函数有一个选项可以clickaction在单击节点时做出响应。但是,我找不到该diagonalNetwork功能的类似选项。还有其他方法可以实现吗?

#### 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)
4

1 回答 1

7

您可以使用htmlwidgets'onRender函数将onclick事件附加到这样的节点......

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)
于 2017-05-25T12:30:16.357 回答