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

基于单选按钮更新澳大利亚COVID-19 Choropleth地图的问题

解决Shiny地图着色错误及动态配色问题

错误原因分析

你遇到的'x' must be numeric错误很容易理解:你直接把input$casetype(这是个字符串类型的列名)传给了调色板函数,但colorQuantile生成的调色板需要的是数值向量,不是列名字符串,自然会报错。

修复步骤及动态配色实现

我们要做两个核心调整:一是动态提取选中字段对应的数值列,二是根据选中字段切换配色方案。下面是完整的修正代码:

完整可运行代码

library(shiny)
library(shinydashboard)
library(leaflet)
library(sf)
library(dplyr)

# 你的病例数据框(可以直接替换成你自己的covid_cases)
covid_cases <- tibble(
  region = c("Australian Capital Territory", "New South Wales", "Northern Territory", 
             "Queensland", "South Australia", "Tasmania", "Victoria", "Western Australia"),
  Confirmed = c(113, 4218, 33, 1157, 468, 230, 20149, 676),
  Deaths = c(3, 53, 0, 6, 4, 13, 787, 9),
  Recovered = c(110, 3118, 31, 1141, 462, 217, 18901, 651)
)

ui <- dashboardBody(
  fluidRow(
    radioGroupButtons(
      inputId = "casetype",
      label = "选择要展示的病例类型:",
      choices = c("Confirmed", "Deaths", "Recovered"),
      selected = "Confirmed"
    ),
    leafletOutput("ausmap")
  )
)

server <- function(input, output) {
  output$ausmap <- renderLeaflet({
    # 读取GeoJSON并关联病例数据
    states_data <- read_sf("https://raw.githubusercontent.com/rowanhogan/australian-states/master/states.geojson") %>% 
      dplyr::left_join(covid_cases, by=c("STATE_NAME" = "region"))
    
    # 1. 建立病例类型与配色的映射关系
    color_mapping <- list(
      Confirmed = "Blues",
      Deaths = "Reds",
      Recovered = "Greens"
    )
    selected_palette <- color_mapping[[input$casetype]]
    
    # 2. 动态提取选中字段的数值,生成对应的调色板
    target_values <- states_data[[input$casetype]]
    pal <- colorQuantile(selected_palette, domain = target_values)
    
    # 渲染交互地图
    leaflet(states_data) %>% 
      addTiles() %>% 
      addPolygons(
        fillColor = ~pal(target_values),
        fillOpacity = 0.8,
        color = "white",
        weight = 1,
        # 可选:添加点击弹窗,展示该州所有病例数据
        popup = ~paste0(
          "<strong>", STATE_NAME, "</strong><br>",
          "确诊病例: ", Confirmed, "<br>",
          "死亡病例: ", Deaths, "<br>",
          "康复病例: ", Recovered
        )
      ) %>% 
      fitBounds(110.246193, -50.322817, 155.226126, -9.088012)
  })
}

shinyApp(ui, server)

关键修改点说明

  • 解决数值错误:用states_data[[input$casetype]]代替固定的states_data$Confirmed,这样能根据用户选择的字段名,动态提取对应的数值向量,完美解决'x' must be numeric的问题。
  • 动态切换配色:创建color_mapping列表,把每个病例类型和对应的色系绑定,用户切换选项时,调色板会自动同步更新。
  • 交互体验优化:额外添加了弹窗功能,用户点击任意州就能查看该州的全部病例数据,让仪表盘更实用。

现在运行这段代码,就能正常切换不同字段的着色,且每个字段对应你想要的配色啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:58:09