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

基于R Shiny实现带复选框的交互式ggbarplot问题求助

修复后的Shiny交互式条形图应用

以下是整合了分组选择、日期筛选功能的完整可运行代码,同时解决了无法绘图/报错的问题:

1. 数据准备(含模拟示例数据)

library(shiny)
library(dplyr)
library(ggplot2)

# 模拟样本采集数据(替换为你的真实数据即可)
sample_data <- data.frame(
  Group = c("A", "A", "B", "C", "B", "A", "C", "C", "B", "A"),
  Collection_Date = as.Date(c(
    "2023-01-05", "2023-02-10", "2023-01-15", "2023-03-20", 
    "2023-02-25", "2023-03-05", "2023-01-30", "2023-02-18",
    "2023-03-10", "2023-01-20"
  ))
)

2. UI部分

ui <- fluidPage(
  titlePanel("样本采集数量统计"),
  
  sidebarLayout(
    sidebarPanel(
      # 日期范围筛选器
      dateRangeInput(
        inputId = "date_range",
        label = "选择采集日期范围:",
        start = min(sample_data$Collection_Date),
        end = max(sample_data$Collection_Date),
        format = "yyyy-mm-dd"
      ),
      
      # 分组选择复选框
      checkboxGroupInput(
        inputId = "selected_groups",
        label = "选择要展示的分组:",
        choices = unique(sample_data$Group),
        selected = unique(sample_data$Group)  # 默认选中所有分组
      )
    ),
    
    mainPanel(
      plotOutput("bar_plot")
    )
  )
)

3. Server部分

server <- function(input, output) {
  
  # 响应式处理数据:根据日期和分组筛选
  filtered_data <- reactive({
    req(input$selected_groups)  # 确保有选中的分组
    
    sample_data %>%
      filter(
        Collection_Date >= input$date_range[1],
        Collection_Date <= input$date_range[2],
        Group %in% input$selected_groups
      ) %>%
      count(Group, name = "Sample_Count")  # 统计每个分组的样本数
  })
  
  # 绘制交互式条形图
  output$bar_plot <- renderPlot({
    req(filtered_data())  # 确保数据存在再绘图
    
    ggplot(filtered_data(), aes(x = Group, y = Sample_Count, fill = Group)) +
      geom_bar(stat = "identity", width = 0.7) +
      labs(
        x = "分组",
        y = "样本采集数量",
        title = "各分组样本采集数量统计"
      ) +
      theme_minimal() +
      theme(plot.title = element_text(hjust = 0.5))
  })
}

# 运行应用
shinyApp(ui = ui, server = server)

关键修复&功能说明

  • 日期格式校验:确保Collection_Date是Date类型,若你的真实数据为字符型,需先用as.Date()转换,避免日期筛选逻辑失效。
  • 响应式数据处理:用reactive()封装筛选逻辑,用户调整输入时数据自动更新。
  • 空值防护:通过req()函数确保存在有效输入和数据后再执行后续代码,避免无选中分组或空数据导致的报错。
  • 默认选中设置:复选框默认选中所有分组,提升初始使用体验。
  • 简化统计逻辑:用dplyr::count()快速完成分组计数,避免手动统计出错。

若你的真实数据列名不同,只需对应修改代码中的列名即可(比如将Group替换为你的分组列名)。

内容的提问来源于stack exchange,提问作者Maria Granell Ruiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:05:18