Shiny应用二次点击Graph按钮后图表消失的问题求助
Shiny应用二次点击Graph按钮后图表消失的问题解决
问题原因
二次点击Graph按钮后图表消失的核心原因是:新生成的所有图表容器默认处于隐藏状态,而负责显示默认选中列的observeEvent(input$choose_column_to_view)没有被自动触发。第一次点击时,pickerInput的初始选中值会触发该事件,但第二次点击时,pickerInput是通过renderUI重新生成的,程序设置的selected值不会触发用户交互类型的事件,导致所有容器保持隐藏,直到手动切换picker才会执行显示逻辑。
修复方案
在点击Graph按钮的逻辑末尾,手动调用shinyjs::show来显示默认选中的列,确保每次生成新图表后,默认选中的内容能自动显示。
修改后的完整代码
choices <- colnames(iris) library(shiny) library(tidyverse) library(bslib) library(glue) library(shinyjs) ui <- fluidPage( useShinyjs(), pickerInput("col_x", "X", choices = choices, multiple = TRUE), actionButton("run", "Graph"), uiOutput("choose_column_ui"), uiOutput("ui") ) server <- function(input, output, session) { reactive_values <- reactiveValues() observeEvent(input$run, { cols <- input$col_x ggplot_string <- map_chr(cols, ~glue("ggplot(iris, aes(x = {.x}, y = Species)) + geom_point() + labs(title = '{.x}')")) all_plots <- map(ggplot_string, ~eval(parse(text = .x))) %>% set_names(cols) # Save all plots to the output lapply(cols, function(x) output[[x]] <- renderPlot(all_plots[[x]])) # Generate all the cards generate_plot_card <- function(column){ hidden(div(id = column, card( card_body(plotOutput(column)), full_screen = TRUE ) ) ) } all_cards <- map(cols, generate_plot_card) default_selected <- cols[[1]] new_picker <- pickerInput("choose_column_to_view", "Choose_col", choices = cols, selected = default_selected, multiple = FALSE) output$choose_column_ui <- renderUI(new_picker) output$ui <- renderUI(tagList(all_cards)) reactive_values$cols <- cols # 新增:手动显示默认选中的列 map(reactive_values$cols, ~shinyjs::hide(id = .x)) shinyjs::show(id = default_selected) }) # Observeevent to show/hide observeEvent(input$choose_column_to_view, { # Hide everything map(reactive_values$cols, ~shinyjs::hide(id = .x)) # Show selected map(input$choose_column_to_view, ~shinyjs::show(id = .x)) }) } shinyApp(ui, server)
关键修改点
在observeEvent(input$run)的最后添加了两段逻辑:
- 先统一隐藏所有列的容器,确保状态一致;
- 手动显示默认选中的列(与picker设置的selected值对应)。
这样每次点击Graph按钮后,都会自动显示默认选中的图表,彻底解决二次点击后图表消失的问题。
内容的提问来源于stack exchange,提问作者MLEN
相关产品推荐
相关产品推荐

