使用ggplot2绘制世界地图时无法为指定国家设置对应填充色
问题原因
原代码仅对马达加斯加、墨西哥、巴西三个国家配置了填充色规则,未加入秘鲁、泰国、肯尼亚的颜色判断逻辑,因此这几个国家默认渲染为灰色。
修正后代码
library(ggplot2) library(dplyr) country.type = map_data("world") country.type <- country.type %>% mutate(fill = case_when( # 绿色组国家 region %in% c("Madagascar", "Mexico", "Brazil") ~ "springgreen", # 黄色组国家 region %in% c("Peru", "Thailand") ~ "yellow", # 红色组国家 region == "Kenya" ~ "red", # 其余国家默认灰色 TRUE ~ "grey80" )) ggplot(country.type, aes(long, lat, fill = fill, group=group)) + geom_polygon(colour="gray80")+ scale_fill_identity()+ theme_classic() + theme(axis.line = element_blank(), axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), panel.background = element_rect(colour= "black", size= 1))
注意事项
如果仍存在指定国家未上色的情况,可运行unique(country.type$region)查看map_data中对应国家的官方拼写,调整匹配即可。
内容的提问来源于stack exchange,提问作者Hector Alexis Luque Machaca
相关产品推荐
相关产品推荐

