如何在Shiny/R中实现两组Tab Panel的同步切换?
实现左右标签页联动切换
要实现点击左侧"Panel 2"时右侧自动切换到"Panel Right Chart 2",需要对代码做以下3处修改:
- 给左右两个
tabsetPanel分别设置ID,让Shiny能捕捉标签切换事件 - 在server端监听左侧标签的切换动作,触发右侧标签页的更新
- 补充加载
ggplot2包(原代码中用到但未加载)
修改后的完整代码如下:
library(shiny) library(ggplot2) # 补充加载绘图包 ui <- fluidPage( column( width = 6, # 给左侧标签页设置ID:left_tabs tabsetPanel( id = "left_tabs", tabPanel( strong("Panel 1") ), tabPanel( strong("Panel 2") ), tabPanel( strong("Panel 3") ))), column( width = 6, # 给右侧标签页设置ID:right_tabs tabsetPanel( id = "right_tabs", tabPanel( strong("Panel Right Chart 1"), plotOutput("chart1") ), tabPanel( strong("Panel Right Chart 2"), plotOutput("chart2") ), tabPanel( strong("Panel Right Chart 3"), plotOutput("chart3") ))) ) server <- function(input, output, session) { # 监听左侧标签页的切换事件 observeEvent(input$left_tabs, { if(input$left_tabs == "Panel 2"){ # 切换右侧标签页到"Panel Right Chart 2" updateTabsetPanel(session, "right_tabs", selected = "Panel Right Chart 2") } # 可选:如果需要其他标签也联动,可继续添加判断 # else if(input$left_tabs == "Panel 1"){ # updateTabsetPanel(session, "right_tabs", selected = "Panel Right Chart 1") # } }) output$chart1 <- renderPlot({ ggplot(mtcars,aes(cyl,mpg)) + geom_line(color = 'red') }) output$chart2 <- renderPlot({ ggplot(mtcars,aes(cyl,mpg)) + geom_line(color = 'green') }) output$chart3 <- renderPlot({ ggplot(mtcars,aes(cyl,mpg)) + geom_line(color = 'blue') }) } shinyApp(ui, server)
如果需要实现所有左侧标签和右侧标签一一联动,只需在observeEvent中补充对应判断即可,代码注释里给出了示例。
内容的提问来源于stack exchange,提问作者Laura
相关产品推荐
相关产品推荐

