【发布时间】:2018-10-17 17:08:08
【问题描述】:
我有一个闪亮的应用程序,我想在其中捕获用户单击的哪个栏并将该值存储在反应式表达式中,以便在其他地方引用以进行过滤。问题是当我切换选项卡时反应表达式会重新运行,因此两个选项卡之间的值不会同步。
我在下面有一个可重现的示例。
当您加载应用程序并单击 Goats 栏时,底部的选择会更改为“Goats”,但如果您随后将选项卡更改为 Bar2,则反应式表达式会重新运行,因此会再次返回 Giraffes。因此,我最终为不同选项卡中的反应式表达式提供了两个单独的值。如果我在第一个选项卡上选择山羊,我希望它在我切换到 Bar2 选项卡时保留,并且仅在我再次单击时更新。
请注意,我意识到我可以在此示例中通过从 event_data 函数中删除源参数来解决此问题,但在我的应用程序中,我有其他图表我不希望用户能够点击,所以我需要设置仅这些图表的来源。
library(shiny)
library(plotly)
library(ggplot2)
library(shinydashboard)
df_test <- data.frame(c("Giraffes","Goats"),c(1,4))
df_test <- setNames(df_test,c("species","amount"))
ui <- dashboardPage(
dashboardHeader(title = "Click Example",
titleWidth = 300),
dashboardSidebar(
width = 300,
sidebarMenu(
menuItem("Tab", tabName = "tab")
)
),
dashboardBody(
tabItems(
tabItem(tabName = "tab",
fluidRow(
column(12, tabBox(
title = "",
id = "tabSet",
width = 12,
height = 500,
tabPanel("Bar1", plotlyOutput(outputId="bar_one")),
tabPanel("Bar2", plotlyOutput(outputId="bar_two"))
)
),
column(12,textOutput(outputId = "selection")))
)
)
)
)
server <- function(input, output, session) {
click_reactive = reactive({
d <- event_data("plotly_click",source=input$tabSet)
if (length(d) == 0) {species = as.vector(df_test$species[1])}
else {species = as.character(d[4])}
return(species)
})
output$bar_one <- renderPlotly({
p <- plot_ly(data = df_test, x = ~amount, y = ~species, type = 'bar', orientation = 'h', source = "Bar1")
})
output$bar_two <- renderPlotly({
p <- plot_ly(data = df_test, x = ~amount, y = ~species, type = 'bar', orientation = 'h', source = "Bar2")
})
output$selection <- renderText({
species <- click_reactive()
return(species)
})
}
shinyApp(ui, server)
【问题讨论】: