在R中使用maps包为指定国家创建全球分级统计图
问题解决:指定国家分级统计图绘制及地图画质优化
一、解决仅目标国家上色的问题
原代码的核心bug是没有将数据中的国家与地图多边形关联,直接把仅4个元素的颜色向量传给col参数,R会自动循环重复颜色,导致大量无关国家被上色。
修改后的完整代码
library(tidyverse) library(maps) df <- tribble( ~Country, ~Value, "Jordan", 35, "USA", 84, "Turkey", 65, "Pakistan", 43 ) percent_map <- function(countries, var, color, legend.title, min = 0, max = 100) { # 生成渐变颜色组 shades <- colorRampPalette(c("white", color))(100) # 约束数值范围并匹配颜色等级 var <- pmax(var, min) var <- pmin(var, max) percents <- as.integer(cut(var, 100, include.lowest = TRUE, ordered = TRUE)) color_mapping <- tibble(Country = countries, fill = shades[percents]) # 获取地图所有区域名称,处理带地区后缀的条目(如"USA:Alaska") world_map_data <- map("world", plot = FALSE) region_colors <- tibble(region = world_map_data$names) %>% mutate(country = str_remove(region, ":.*")) %>% left_join(color_mapping, by = c("country" = "Country")) %>% mutate(fill = ifelse(is.na(fill), "transparent", fill)) # 未匹配国家设为透明 # 绘制地图 map("world", fill = TRUE, col = region_colors$fill, resolution = 1, mar = c(0,0,0,0)) # 叠加白色国界 map("world", col = "white", fill = FALSE, add = TRUE, lty = 1, lwd = 1, mar = c(0,0,0,0)) # 新增图例(可选) legend("bottomright", legend = c(min, max), fill = c(shades[1], shades[100]), title = legend.title, bty = "n") } # 调用函数,必须传入国家列 percent_map(countries = df$Country, var = df$Value, color = "darkgreen", legend.title = "Global Map for Value", min = 0, max = 100 )
关键修改点
- 新增
countries参数,传入数据中的国家名称列 - 提取地图所有区域名称,去除地区后缀后和数据中的国家匹配
- 未匹配到的国家填充色设为
transparent,实现无色效果
二、地图画质优化
画质低的原因
原代码设置了resolution = 0,这是maps包的最低分辨率选项,对应最粗略的地图轮廓数据,所以画质模糊。
两种优化方案
方案1:提升maps包内置分辨率
把resolution参数改为1,这是maps包内置的高分辨率选项:
map("world", fill = TRUE, col = region_colors$fill, resolution = 1, # 切换到高分辨率 mar = c(0,0,0,0))
方案2:使用mapdata包的高清地图
如果内置高分辨率仍不够,可以使用mapdata包提供的worldHires数据集,画质会精细很多:
# 先安装包 install.packages("mapdata") library(mapdata) # 修改绘制代码,替换为worldHires map("worldHires", fill = TRUE, col = region_colors$fill, mar = c(0,0,0,0)) # 叠加国界也要同步替换 map("worldHires", col = "white", fill = FALSE, add = TRUE, lty = 1, lwd = 1, mar = c(0,0,0,0))
内容的提问来源于stack exchange,提问作者rez
相关产品推荐
相关产品推荐

