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

使用R语言usmap库绘制县级数据地图的报错及优化需求咨询

问题修复与实现方案

1. 报错原因与修复

报错核心原因:plot_usmap的data参数要求传入包含fips列和数值列的完整数据框,你当前分别传入两个独立向量,不符合参数格式要求;若你的fips列名不是默认的fips,还需要通过fips参数指定对应列名。
修复后的单日期绘图代码如下:

library(usmap)
library(ggplot2)
library(RColorBrewer)

setwd("C:/Users/Name/Documents/RScripts/")
usa.dat <- read.csv("covid.csv", header = T)

plot_usmap(regions = "counties",
           data = usa.dat,
           values = "X1.22.2020",
           fips = "countyFIPS") +
  theme(panel.background = element_rect(color = "black", fill = "black"))

2. 自定义颜色渐变方案

直接追加ggplot的填充色标度函数即可调整配色,两种常用方案示例如下:

方案1:自定义双色渐变

plot_usmap(regions = "counties",
           data = usa.dat,
           values = "X1.22.2020",
           fips = "countyFIPS") +
  scale_fill_gradient(low = "#fde725", high = "#440154", 
                      na.value = "gray30", # 无数据的县域填充色
                      name = "死亡人数") + # 图例名称
  theme(panel.background = element_rect(color = "black", fill = "black"),
        legend.background = element_rect(fill = "black"),
        legend.text = element_text(color = "white"),
        legend.title = element_text(color = "white"))

方案2:使用RColorBrewer多阶配色

plot_usmap(regions = "counties",
           data = usa.dat,
           values = "X1.22.2020",
           fips = "countyFIPS") +
  scale_fill_distiller(palette = "YlOrRd", # 可选RdBu、Greens等其他RColorBrewer配色名
                       direction = 1, 
                       na.value = "gray30",
                       name = "死亡人数") +
  theme(panel.background = element_rect(color = "black", fill = "black"))

3. 实现逐帧动画

使用gganimate包实现,先将宽格式的原始数据转换为长格式,再添加动画过渡参数即可,示例代码如下:

library(gganimate)
library(tidyr)
library(dplyr)

# 宽格式转长格式
usa_long <- usa.dat %>%
  pivot_longer(cols = starts_with("X"), # 匹配所有日期列
               names_to = "date",
               values_to = "death") %>%
  # 转换日期格式,方便动画按时间排序
  mutate(date = as.Date(date, format = "X%m.%d.%Y"))

# 绘制动画地图
p <- plot_usmap(regions = "counties",
                data = usa_long,
                values = "death",
                fips = "countyFIPS") +
  scale_fill_distiller(palette = "YlOrRd",
                       na.value = "gray30",
                       name = "死亡人数") +
  theme(panel.background = element_rect(color = "black", fill = "black"),
        legend.background = element_rect(fill = "black"),
        legend.text = element_text(color = "white"),
        legend.title = element_text(color = "white"),
        plot.title = element_text(color = "white", size = 16, hjust = 0.5)) +
  # 自动匹配当前帧日期作为标题
  labs(title = "美国新冠死亡人数:{frame_time}") +
  # 按日期设置过渡动画
  transition_time(date)

# 导出为gif,可调整fps、时长、分辨率参数
anim_save("covid_death_animation.gif", p, fps = 10, duration = 30, width = 1200, height = 800)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:15:02