You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)的最后添加了两段逻辑:

  1. 先统一隐藏所有列的容器,确保状态一致;
  2. 手动显示默认选中的列(与picker设置的selected值对应)。

这样每次点击Graph按钮后,都会自动显示默认选中的图表,彻底解决二次点击后图表消失的问题。

内容的提问来源于stack exchange,提问作者MLEN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 07:20:00