R绘制莱索托行政区气象风险地图报错:未找到region对象
问题概述
需要用R绘制莱索托10个行政区的气象风险等级地图,现有代码在执行筛选地图数据步骤时报错:
Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function '%in%': object 'region' not found.
错误原因
- 语法层面:代码使用了
dplyr包的管道%>%、filter等函数,但未加载dplyr,导致函数环境无法识别数据列。 - 核心逻辑:
map_data('world')仅提供国家级别的地理边界,不包含莱索托的次级行政区数据,因此无法通过行政区名称筛选到对应地理信息。
解决方案
第一步:修复语法问题(基础修正)
在代码开头添加dplyr包的加载语句,确保管道和数据处理函数能正常运行:
library(dplyr)
但此修正无法解决核心的行政区边界缺失问题,需使用以下方法获取莱索托行政区数据。
第二步:获取莱索托行政区边界(核心解决方法)
推荐使用rnaturalearth包获取官方标准化的行政区空间数据,以下是完整可运行代码:
# 安装所需包(首次运行时执行) install.packages(c("sf", "ggplot2", "dplyr", "rnaturalearth", "rnaturalearthdata")) # 加载包 library(sf) library(ggplot2) library(dplyr) library(rnaturalearth) library(rnaturalearthdata) # 定义各行政区风险数据 all_districts <- data.frame( name = c("Maseru", "Butha-Buthe", "Leribe", "Berea", "Mafeteng", "Mohale's Hoek", "Quthing", "Qacha's Nek", "Mokhotlong", "Thaba-Tseka"), risk = c(4, 4, 2, 1, 2, 4, 1, 3, 1, 2) ) # 获取莱索托一级行政区空间数据 lesotho_districts <- ne_states(country = "Lesotho", returnclass = "sf") # 合并空间数据与风险数据(确保name列拼写完全匹配) mapdata_x <- lesotho_districts %>% left_join(all_districts, by = "name") # 绘制风险地图 ggplot(mapdata_x) + geom_sf(aes(fill = factor(risk)), linewidth = 0.25, color = "black") + scale_fill_manual(values = c("#a6d96a", "#ffffbf", "#fdae61", "#d7191c"), name = "Risk Level") + theme_void() + # 一键隐藏所有无关轴元素,适配地图展示 labs(title = "Lesotho Weather Risk Levels") + geom_sf_text(aes(label = name), size = 3) # 精准标注行政区名称
替代方法:使用本地Shapefile
若无法联网安装rnaturalearth,可从地理数据平台下载莱索托行政区Shapefile,再通过sf包读取:
# 读取本地Shapefile(替换为实际文件路径) lesotho_districts <- st_read("your/path/to/lesotho_adm1.shp") # 后续合并数据、绘图步骤与上述代码一致
关键提示
- 确保
all_districts里的行政区名称与空间数据中的name列拼写完全一致(包括大小写、特殊字符),否则会出现匹配失败。 theme_void()是ggplot2专为地图设计的主题,比手动逐个隐藏轴元素更简洁高效。
内容的提问来源于stack exchange,提问作者Zilore Mumba
相关产品推荐
相关产品推荐

