Shiny中如何实现按by字段分组绘图并支持全量数据展示
Shiny 全量/分组切换绘图实现方案
核心改动只有两处:给分组选择器新增全量数据选项、渲染绘图时按用户选择过滤数据集,调整后代码可直接运行:
核心修改点
- 侧边栏下拉选择器新增
"全量数据"作为默认选项,保留原有分组值供切换 - 服务端先判断用户选中的范围:选全量时使用完整原始数据,选具体分组时先按
by字段筛选匹配子集 - 排序、颜色赋值等数据处理逻辑全部基于过滤后的数据集执行,保证不同视图下样式规则统一
library(shiny) library(ggplot2) library(dplyr) ui <- fluidPage( titlePanel("全量/分组切换绘图"), sidebarLayout( sidebarPanel( width = 2, selectInput( inputId = "by", label = "数据范围", choices = c("全量数据", "by.1", "by.2"), selected = "全量数据" ) ), mainPanel( plotOutput("distPlot") ) ) ) server <- function(input, output) { output$distPlot <- renderPlot({ # 原始数据集 raw_df <- data.frame( dose = c("D0.5", "D1", "D2", "D3", "D4", "D5"), len = c(4.2, 10, 29.5, 5, 7, 15), by = c("by.1", "by.1","by.1","by.2","by.2","by.2") ) mycols <- c("#92d050", "#57d3ff", "#ffc000") # 按选择过滤绘图数据 plot_df <- if(input$by == "全量数据") { raw_df } else { raw_df %>% filter(by == input$by) } # 基于过滤后的数据做排序、颜色映射 plot_df <- plot_df %>% arrange(desc(len)) %>% mutate(fills = ifelse(row_number() <= length(mycols), mycols, "grey50")) # 绘图 ggplot(data = plot_df, aes(x = len, y = reorder(dose, len))) + geom_col(aes(fill = I(fills)))+ geom_text(aes(x = len/2, label = glue::glue("{dose} ({len}%)"))) + theme_minimal() + scale_x_continuous(NULL, expand = c(0,0)) + theme( axis.ticks.y = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank() ) }) } shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者symkly
相关产品推荐
相关产品推荐

