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

如何用bslib在Shiny中实现可导航的Bootstrap风格侧边栏

用bslib实现Bootstrap风格侧边栏及页面导航

1. 关于bslib的侧边栏函数

bslib提供了直接的sidebar()函数——你代码里已经在使用它了,这个函数就是专门用来创建符合Bootstrap风格的侧边栏组件的,完全可以实现你参考的Bootstrap官网侧边栏效果。

2. 实现侧边栏导航与主面板页面切换

要实现点击侧边栏选项切换主面板内容,核心是用侧边栏导航链接绑定主面板的标签页组件,以下是改造后的完整代码(替换了你原有的变量选择输入,实现多页面切换):

library(bslib)
library(shiny)
library(ggplot2)
library(corrplot)

ui <- page_sidebar(
  title = "Example dashboard",
  # 改造后的导航侧边栏
  sidebar = sidebar(
    width = 250, # 调整宽度贴近Bootstrap示例
    collapsible = TRUE, # 支持折叠功能
    nav(
      class = "flex-column", # 垂直导航布局
      nav_link("数据概览", value = "tab_overview"),
      nav_link("变量分布", value = "tab_dist"),
      nav_link("相关性分析", value = "tab_corr")
    )
  ),
  # 主面板:可切换的标签页容器
  navset_card_tab(
    full_screen = TRUE,
    nav_panel("数据概览", value = "tab_overview",
              card_header("数据集基本信息"),
              verbatimTextOutput("data_summary")
    ),
    nav_panel("变量分布", value = "tab_dist",
              card_header("变量直方图"),
              varSelectInput("var", "选择变量", mtcars),
              plotOutput("hist_plot")
    ),
    nav_panel("相关性分析", value = "tab_corr",
              card_header("变量相关性矩阵"),
              plotOutput("corr_plot")
    )
  )
)

server <- function(input, output) {
  # 数据概览内容
  output$data_summary <- renderPrint({
    summary(mtcars)
  })
  
  # 变量分布直方图
  output$hist_plot <- renderPlot({
    ggplot(mtcars) + 
      geom_histogram(aes(!!input$var), bins = 10, fill = "#0d6efd", alpha = 0.7)
  })
  
  # 相关性矩阵图
  output$corr_plot <- renderPlot({
    corr_matrix <- cor(mtcars)
    corrplot(corr_matrix, method = "circle", type = "upper")
  })
}

shinyApp(ui, server)

关键实现细节

  • sidebar()内的nav(class = "flex-column")实现垂直导航布局,和Bootstrap示例的侧边栏样式一致;
  • nav_link()的value属性与nav_panel()的value一一对应,点击侧边栏链接会自动切换主面板的标签页;
  • 给sidebar()添加collapsible = TRUE可以实现Bootstrap示例中的侧边栏折叠功能,添加sidebar_position = "fixed"到page_sidebar()可固定侧边栏位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:25:20