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

使用gganimate绘制地图时遇Error: arguments have different crs错误求助

解决Error: arguments have different crs问题

问题根源有两个:

  • 国家名称直接匹配不准确,导致大量行缺失几何信息(geometry为NA)
  • 缺失几何信息的行干扰了gganimate对sf对象CRS的统一识别

修改步骤:

  1. 统一国家编码匹配:用countrycode将artist_country转换为ISO3代码,再与world的iso_a3字段关联,避免名称不匹配问题。
  2. 过滤无效几何行:移除没有有效几何信息的行,确保所有行的CRS一致。
  3. 确认CRS统一:显式设置sf对象的CRS为WGS84(EPSG:4326),避免潜在的CRS偏差。

修改后的完整代码:

library(tidyverse)
library(sf)
library(rnaturalearth)
library(countrycode)
library(gganimate)
library(transformr)

# 获取世界地图数据,指定CRS为WGS84
world <- ne_countries(scale = "medium", returnclass = "sf") %>%
  st_set_crs(4326)

eurovision <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-05-17/eurovision.csv')

to_plot <- eurovision %>% 
  select(year, artist_country, section, winner) %>% 
  mutate(
    winnings = case_when(
      str_detect(section, "^grand-final$|^final$") & winner == TRUE ~ 1,
      TRUE ~ 0
    ),
    # 将国家名称转换为ISO3代码,用于匹配地图数据
    iso_a3 = countrycode(artist_country, origin = "country.name", destination = "iso3c")
  ) %>%
  # 用ISO3代码关联地图数据,避免名称不匹配
  left_join(world, by = "iso_a3") %>%
  # 过滤掉没有有效几何信息的行
  filter(!st_is_empty(geometry)) %>%
  select(year, admin, winnings, geometry) %>%
  arrange(year) %>% 
  group_by(admin) %>% 
  mutate(winnings = lag(cumsum(winnings), default = 0)) %>% 
  ungroup() %>%
  # 显式统一CRS
  st_set_crs(4326)

to_plot %>% 
  ggplot() + 
  geom_sf(aes(fill = winnings)) +  # 无需重复指定geometry,sf对象会自动识别
  coord_sf(xlim = c(-25, 50), ylim = c(30, 80), expand = FALSE) +
  scale_fill_viridis_c(option = 1) + 
  labs(title = "{frame_time}") + 
  transition_time(year)

关键修改说明:

  • 用countrycode转换国家编码,解决了"UK"、"USA"等简称无法匹配地图全称的问题
  • 添加filter(!st_is_empty(geometry))移除无效几何行,确保每个frame的sf对象都有统一的CRS
  • 显式调用st_set_crs(4326)两次,分别在获取地图数据和处理后的数据上,彻底统一CRS
  • 移除geom_sf中的geometry = geometry参数,sf对象会自动识别几何列,简化代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:15:23