我们创建了桑基图,通过R中的networkD3::sankeyNetwork()
显示不同城市之间的流动。我们收到客户要求在桑基节点的工具提示/悬停上显示与城市相对应的"状态"名称。
下面的代码中,我们希望在节点的工具提示(悬停(上显示状态值
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)
由于networkD3
包不提供自定义的工具提示功能,因此请建议如何通过javascript或其他方式实现networkD3::sankeyNetwork()
。
您可以使用类似于此堆栈溢出答案的技术。保存 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)