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

使用R的raster包为指定国家省份自定义着色问题求解

问题原因

你遇到的颜色对应错误核心原因是id匹配错位:

  • fortify(iran)生成的地图数据里,id默认从0开始计数,取值范围是0~30,对应31个省份
  • 你构造dat数据框时用的id是1~31,两个表做inner_join时,每个省份的属性整体错位了1位,自然颜色就不对。

修复后完整代码

library(raster)
library(rgeos)
library(ggplot2)
library(dplyr)

# 读取地图数据
iran <- getData("GADM", country = "Iran", level = 1)
map <- fortify(iran)
# 修复id:fortify的id从0开始,加1后和dat的1~31对齐
map$id <- as.integer(map$id) + 1

dat <- data.frame(id = 1:(length(iran@data$NAME_1)),
                  state = iran@data$NAME_1,
                  pr = c(530, -42, 1673, 75, 206, 544, 1490, 118, 75,
                         40, 105, 191, 111, 810, 609, 425, 418, 550, 40, 425, -54, -50,
                         16, 18, 133,425, -30, 241,63, 191,100))
dat <- dat %>% mutate(color_province = case_when(pr <= 50 ~ 'green',
                                                 pr > 150 ~ 'red',
                                                 TRUE ~ 'yellow'))

# 关联数据
map_df <- inner_join(map, dat, by = "id")
centers <- data.frame(gCentroid(iran, byid = TRUE))
centers$state <- dat$state

# 绘图
ggplot() +  
  geom_polygon(data = map_df, 
               aes(x = long, y = lat, group = group, fill = color_province),
               color = "white") + # 加白色省界方便区分省份
  geom_text(data = centers, aes(label = state, x = x, y = y), size = 3) +
  coord_map() +
  labs(x = "", y = "", title = "Iran Province") +
  scale_fill_manual(values = c("green" = "green", "red" = "red", "yellow" = "yellow")) +
  theme_bw()

修改说明

  1. 给map$id加了1,确保和dat的id从1开始的规则完全对齐
  2. 把容易出参数匹配问题的geom_map换成了更直观的geom_polygon,避免额外的匹配错误
    修改后阿尔达比勒省就会显示为绿色,赞詹省显示为黄色,和你dat里的定义完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:06:07