以下R闪亮脚本会创建一个sankey图表,如下面的快照所示。我的要求是当我点击左右节点之间的任何链接时,即" a1"和" a2",我想要相应的" a3"的总和。出现在标签上。对于插图," A"在a1和" E"在a2中一起有50和32的值。所以,我想在点击链接时看到标签中的82,请帮助和谢谢。与其他所有a1,a2对相似。下面的服务器代码中的list()函数需要进行一些调整。附加快照。
library(shiny)
library(shinydashboard)
library(plotly)
library(DT)
library(dplyr)
a1 = c("A","B","C","A","C","C","B")
a2 = c("E","F","G","E","G","G","F")
a3 = c(50,45,64,32,45,65,75)
a12 = data.frame(a1,a2,a3,stringsAsFactors = FALSE)
a12$a1 = as.character(a12$a1)
a12$a2 = as.character(a12$a2)
ui <- dashboardPage(
dashboardHeader(title = "Sankey Chart"),
dashboardSidebar(
width = 0
),
dashboardBody(
box(title = "Sankey Chart", status = "primary",height = "455" ,solidHeader =
T,plotlyOutput("sankey_plot")),
box( title = "Case Summary", status = "primary", height = "455",solidHeader
= T, dataTableOutput("sankey_table"))
))
server <- function(input, output)
{
sankeyData <- reactive({
sankeyData <- a12 %>%
group_by(a1,a2) %>%
count()
sankeyNodes <- list(label = c(sankeyData$a1,sankeyData$a2) %>% unique())
trace2 <- list(
domain = list(
x = c(0, 1),
y = c(0, 1)
),
link = list(
label = paste0("Case",1:nrow(sankeyData)),
source = sapply(sankeyData$a1,function(e) {which(e ==
sankeyNodes$label) },
USE.NAMES = FALSE) - 1,
target = sapply(sankeyData$a2,function(e) {which(e ==
sankeyNodes$label) },
USE.NAMES = FALSE) - 1,
value = sankeyData$n
),
node = list(label = sankeyNodes$label),
type = "sankey"
)
trace2
})
output$sankey_plot <- renderPlotly({
trace2 <- sankeyData()
p <- plot_ly()
p <- add_trace(p, domain=trace2$domain, link=trace2$link,
node=trace2$node, type=trace2$type)
p
})
output$sankey_table <- renderDataTable({
d <- event_data("plotly_click")
req(d)
trace2 <- sankeyData()
sIdx <- trace2$link$source[d$pointNumber+1]
Source <- trace2$node$label[sIdx + 1 ]
tIdx <- trace2$link$target[d$pointNumber+1]
Target <- trace2$node$label[tIdx+1]
a12 %>% filter(a1 == Source & a2 == Target)
})
}
shinyApp(ui, server)