R Shiny时间序列图如何新增「全类别」展示选项
R Shiny 新增「全类别」单选选项实现方案
核心修改要点
- 下拉选项层:在原有单类别选项列表的最前端,新增内部标记为
"ALL"的「全类别」选项,完全保留原有单选交互逻辑,不会影响原有的单类别选择流程 - 数据筛选层:在服务端逻辑中新增分支判断,当用户选中值为
"ALL"时不对类别字段做过滤,返回全量时间序列数据;选中其他单类别值时,保持原有的单值过滤逻辑 - 绘图逻辑修正:同步修复原代码中两处会导致功能失效的小问题:
- 原代码中filter后直接在ggplot里指定全局原始数据集的写法,会让过滤逻辑完全失效,需移除
ggplot()中重复引用全局数据集的写法,直接使用管道传递的过滤后数据集做映射 - 原代码中
scale_fill_economist()与折线的colour映射不匹配,不会产生配色效果,需替换为scale_colour_economist(),保证经济学家主题的配色能正常作用于折线
- 原代码中filter后直接在ggplot里指定全局原始数据集的写法,会让过滤逻辑完全失效,需移除
完整可运行修改后代码
rm(list=ls()) library(shiny) library(shinyWidgets) library(ggplot2) library(dplyr) library(readxl) library(scales) library(ggthemes) library(plotly) data <- read_excel("C:/Users/Kanew/OneDrive/Desktop/RApp/Unemployment2.xlsx") data$Date <- as.Date(data$MonthYear) ui <- fluidPage( h1("National Unemployment Rate by Race"), selectInput( inputId = "Category", label = "Select Race or National Rate", # 新增全类别选项,前端展示「全类别」,内部传值为"ALL"供程序判断 choices = c("全类别" = "ALL", unique(data$Category)), selected = "National" ), plotlyOutput("plot"), setBackgroundColor("#778899") ) server <- function(input, output, session) { output$plot <- renderPlotly({ # 分支实现差异化筛选 target_data <- if (input$Category == "ALL") { data } else { data %>% filter(Category == input$Category) } target_data %>% ggplot(mapping = aes(x = Date, y = Rate, colour = Category)) + geom_line() + xlab("Year") + ylab("Unemployment Rate (%)") + scale_y_continuous(breaks = c(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)) + scale_x_date(date_breaks = "years", date_labels = "%Y") + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + theme_economist() + scale_colour_economist() }) } shinyApp(ui, server)
后续多类别对比功能扩展提示
后续要实现多类别自定义对比功能时,仅需将原有的selectInput替换为支持多选的pickerInput组件,再将筛选逻辑调整为filter(Category %in% input$Category)即可,无需改动核心绘图代码。
内容的提问来源于stack exchange,提问作者Kane Wong
相关产品推荐
相关产品推荐

