You need to enable JavaScript to run this app. 在Shiny Dashboard中实现多图表关联的城市大小写不敏感搜索功能
优惠活动
大模型
产品
解决方案
定价
更多

在Shiny Dashboard中实现多图表关联的城市大小写不敏感搜索功能

Shiny Dashboard 不区分大小写城市搜索功能实现

核心实现逻辑为:将用户输入的搜索内容与数据框中城市字段统一转换为大写格式后匹配,同时加入城市不存在时的提示逻辑,动态过滤数据生成对应图表。

修改后的完整可运行代码

library(easypackages)
libraries("shiny","shinydashboard","tidyverse","lubridate", "plotly","Rcpp")
theme_set(theme_minimal())

# 构造模拟数据集
city <- c("NAIROBI", "MOMBASA", "MOMBASA","MOMBASA","NAIROBI")
SalesCount <- c(34, 50, 23, 70, 33)
Qualifications <- c("More than one", "One","One", "More than one","One")
Age <- c(45, 50, 43, 44, 60)
SalesDF <- data.frame(city, SalesCount, Qualifications, Age)

ui <- fluidPage(
  titlePanel("销售数据看板"),
  sidebarLayout(
    sidebarPanel(
      sidebarMenu(
        sidebarSearchForm(textId = "Search", buttonId = "searchTown",
                          label = "搜索城市")
      )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("城市销量统计", plotOutput("plot1")),
        tabPanel("资质对应销量统计", plotOutput("plot2"))
      )
    )
  )
)

server <- function(input, output) {
  # 响应搜索请求,返回过滤后的数据集
  filtered_sales <- reactive({
    # 处理用户输入:去除首尾空格、转换为大写,匹配原数据格式
    input_city <- toupper(trimws(input$Search))
    res <- dplyr::filter(SalesDF, city == input_city)
    # 校验匹配结果,无匹配则返回提示
    validate(
      need(nrow(res) > 0, "City not found")
    )
    return(res)
  })
  
  # 动态生成城市销量图表
  output$plot1 <- renderPlot({
    ggplot(filtered_sales(), aes(city, SalesCount)) + 
      geom_col(fill = "#2c3e50") +
      labs(x = "城市", y = "销量")
  })
  
  # 动态生成资质对应销量图表
  output$plot2 <- renderPlot({
    ggplot(filtered_sales(), aes(Qualifications, SalesCount)) + 
      geom_col(fill = "#3498db") +
      labs(x = "资质情况", y = "销量")
  })
}

shinyApp(ui = ui, server = server)

功能验证说明

  • 输入任意大小写格式的NAIROBI/MOMBASA,都会匹配到对应城市的数据,生成对应统计图表
  • 输入不存在的城市名称,两张图表位置都会统一显示City not found的错误提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 22:27:03