You need to enable JavaScript to run this app. 如何获取Shiny中bs_accordion激活面板状态以联动输入生成对应绘图
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Shiny中bs_accordion激活面板状态以联动输入生成对应绘图

实现方案

状态捕获机制

bsplus 包对 bs_accordion 组件内置了Shiny输入绑定:只要给accordion定义固定的id,服务端就能直接通过input$<accordion_id> 拿到当前处于展开激活状态的面板标识,不需要额外写自定义JS或者shinyjs的监听逻辑。

  • 这个标识默认和bs_append()传入的title参数一致,也可以在bs_append()里通过value参数指定固定字符串,避免后续修改面板标题时打乱服务端的判断逻辑。
  • 同一时间这个输入值只会返回一个被激活的面板标识,完全适配分支判断的场景。

需要修正的原有代码问题

  • 原代码存在拼写错误:数据框名写成了day_dat,实际定义的是day_data,直接运行会报找不到对象的错误。
  • 原有的数据判断逻辑完全错位:原来的判断逻辑是只要月维度的选择框有值,就永远优先取月维度数据,哪怕用户已经展开了日维度的面板、选了日维度的区域,也不会切换绘图内容,完全没和面板状态关联。
  • 缺少初始状态校验:accordion刚加载的时候是全折叠状态,此时激活面板的输入值为NULL,如果不做拦截,绘图逻辑会因为取不到对应输入而报错。

调整后的可运行完整代码

library(shiny)
library(bsplus)
library(shinyjs)

month_data <- data.frame(Region = c(rep("Region M1", 20), rep("Region M2", 20)),
                         Value = runif(40))
day_data <- data.frame(Region = c(rep("Region D3", 20), rep("Region D4", 20)),
                       Value = runif(40))


m1 <- selectInput(inputId = "in_month_region", label = "Region", choices = c("Region M1", "Region M2"))
d1 <- selectInput(inputId = "in_day_region", label = "Region", choices = c("Region D3", "Region D4"))

ui <- fluidPage(
  
  useShinyjs(),
  
  actionButton(inputId = "toggle_menu", label = "Options"),
  
  br(),
  
  sidebarLayout(
    
    div(id = "Sidebar", 
        sidebarPanel(width = 3,
                     bs_accordion(id = "input_panel") %>%
                       bs_set_opts(panel_type = "success", use_heading_link = TRUE) %>%
                       # 给每个面板指定固定的value标识,避免标题修改影响判断
                       bs_append(title = "Monthly", 
                                 content = m1,
                                 value = "month") %>%
                       bs_append(title = "Daily", 
                                 content = d1,
                                 value = "day"))),
    
    mainPanel(plotOutput("myplot"))
    
  )
  
  
)




server <- function(input, output, session){
  
  observeEvent(input$toggle_menu, {
    shinyjs::toggle(id = "Sidebar")
  })
  
  get_data <- reactive({
    current_active_panel <- input$input_panel
    req(current_active_panel) # 无激活面板时直接终止计算,避免报错
    
    if(current_active_panel == "month"){
      subset(month_data, Region %in% input$in_month_region)
    } else if(current_active_panel == "day"){
      # 修正原代码的拼写错误
      subset(day_data, Region %in% input$in_day_region)
    }
  })
  
  
  
  output$myplot <- renderPlot({
    req(get_data())
    mydat <- get_data()
    plot(mydat$Value, main = unique(mydat$Region))
  })
  
}


shinyApp(ui, server)

联动效果

  • 展开哪个面板,就自动读取对应面板里的输入值,匹配对应的数据源生成绘图
  • 哪怕两个面板的输入框都选过值,绘图内容也会严格跟随当前激活的面板切换
  • 所有面板折叠时,绘图区域保持空白,不会触发运行报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.04 02:15:05