networkD3::sankeyNetwork 中的 R-Customized tooltip

Sou*_*mar 3 javascript r shiny sankey-diagram networkd3

我们已经创建了 sankey 图来通过networkD3::sankeyNetwork()R显示不同城市之间的流量。我们已经收到客户要求在 sankey 节点的工具提示/悬停上显示与城市对应的“状态”名称。

在以下代码中,我们希望在节点的工具提示(悬停)上显示状态值

library(shiny)
library(networkD3)
library(shinydashboard)
value <-  c(12,21,41,12,81)
source <- c(4,1,5,2,1)
target <- c(0,0,1,3,3)

edges2 <- data.frame(cbind(value,source,target))

names(edges2) <- c("value","source","target")
indx  <- c(0,1,2,3,4,5)
ID    <- c('CITY1','CITY2','CITY3','CITY4','CITY5','CITY6')
State <- c( 'IL','CA','FL','NW','GL','TX')
nodes <-data.frame(cbind(ID,indx,State))

ui <- dashboardPage(
  dashboardHeader(
  ),
  dashboardSidebar(disable = TRUE),
  dashboardBody(
    fluidPage(
      sankeyNetworkOutput("simple")
    )
  )
)

server <- function(input, output,session) {
  
  
  output$simple <- renderSankeyNetwork({
    sankeyNetwork(Links = edges2, Nodes = nodes,
                  Source = "source", Target = "target",
                  Value = "value",  NodeID = "ID" 
                  ,units = " " )
  })
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

由于该networkD3包不提供自定义工具提示功能,请建议如何通过 javascript 或networkD3::sankeyNetwork().

CJ *_*man 6

您可以使用类似于此Stack Overflow 答案的技术。保存sankeyNetwork函数的输出,然后重新添加被剥离的数据,然后使用htmlwidgets::onRender添加一些 JavaScript 来修改节点的工具提示文本......

library(shiny)
library(networkD3)
library(shinydashboard)
value <-  c(12,21,41,12,81)
source <- c(4,1,5,2,1)
target <- c(0,0,1,3,3)

edges2 <- data.frame(cbind(value,source,target))

names(edges2) <- c("value","source","target")
indx  <- c(0,1,2,3,4,5)
ID    <- c('CITY1','CITY2','CITY3','CITY4','CITY5','CITY6')
State <- c( 'IL','CA','FL','NW','GL','TX')
nodes <-data.frame(cbind(ID,indx,State))

ui <- dashboardPage(
    dashboardHeader(
    ),
    dashboardSidebar(disable = TRUE),
    dashboardBody(
        fluidPage(
            sankeyNetworkOutput("simple")
        )
    )
)

server <- function(input, output,session) {


    output$simple <- renderSankeyNetwork({
        sn <- sankeyNetwork(Links = edges2, Nodes = nodes,
                      Source = "source", Target = "target",
                      Value = "value",  NodeID = "ID" 
                      ,units = " " )

        # add the states back into the nodes data because sankeyNetwork strips it out
        sn$x$nodes$State <- nodes$State

        # add onRender JavaScript to set the title to the value of 'State' for each node
        sn <- htmlwidgets::onRender(
            sn,
            '
            function(el, x) {
                d3.selectAll(".node").select("title foreignObject body pre")
                .text(function(d) { return d.State; });
            }
            '
        )

        # return the result
        sn
    })
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)