R语言绘制世界地图无颜色问题:需安装新包或修改代码?
R地球地图函数与人口地图无颜色问题解决
一、可显示地球地图的R函数/工具
- highcharter:支持交互式3D地球(
hc_chart(type = "globe")),也可通过GeoJSON数据绘制平面世界地图,适合做可视化交互效果 - ggplot2 + 地理扩展包:结合
map_data("world")获取基础地图数据,用geom_polygon绘制,搭配coord_sf(crs = "+proj=ortho")可实现球面投影的地球效果 - leaflet:加载在线底图(如OpenStreetMap),添加行政区图层,支持缩放、点击交互,适合嵌入式网页地图
二、人口地图无颜色问题排查与修复
地图显示但无颜色,核心原因是数据匹配失败或颜色配置缺失,按以下步骤排查:
确认GeoJSON与数据框的字段匹配
- 查看GeoJSON文件中的国家名称字段:执行
names(worldgeojson$features[[1]]$properties),找到对应国家名称的字段(比如name、admin) - 修改
joinBy参数为c("GeoJSON字段名", "Country"),确保两边国家名称完全一致(注意大小写、全称/简称差异,比如"US" vs "United States")
- 查看GeoJSON文件中的国家名称字段:执行
验证Population数据类型
- 执行
class(population$Population),确保是数值型;如果是字符型,转换为数值:population$Population <- as.numeric(population$Population)
- 执行
完善颜色轴配置
- 给
color_stops()指定具体颜色范围,同时设置数值区间,避免因数据范围识别失败导致无颜色:hc_colorAxis( min = min(population$Population, na.rm = TRUE), max = max(population$Population, na.rm = TRUE), stops = color_stops(colors = c("#f0f9e8", "#006d2c")) )
- 给
检查数据匹配情况
- 找出未匹配的国家,手动修正名称:
# 提取GeoJSON中的所有国家名称 map_countries <- sapply(worldgeojson$features, function(x) x$properties$name) # 查看不匹配的国家 unmatched <- dplyr::anti_join(population, dplyr::tibble(Country = map_countries), by = "Country") print(unmatched)
- 找出未匹配的国家,手动修正名称:
修正后的完整代码示例
library(highcharter) library(dplyr) # 预处理数据:确保Population为数值型 population <- baza %>% select(Country, Population) %>% mutate(Population = as.numeric(Population)) # 检查GeoJSON字段并匹配 map_country_field <- "name" # 替换为你的GeoJSON实际字段名 highchart() %>% hc_add_series_map(worldgeojson, df = population, value = "Population", joinBy = c(map_country_field, "Country")) %>% hc_colorAxis( min = min(population$Population, na.rm = TRUE), max = max(population$Population, na.rm = TRUE), stops = color_stops(colors = c("#e5f5f9", "#2ca25f")) ) %>% hc_title(text = "World Population") %>% hc_tooltip(useHTML = TRUE, formatter = JS( "function(){" , " return '<b><u>'+this.point.Country+'</u></b><br>'" , " +'<b>Population:</b> '+parseInt(this.point.value);" , "}" ) ) %>% hc_legend( enabled = TRUE, title = list(text = "Population"), layout = "vertical", align = "right", verticalAlign = "middle" )
内容的提问来源于stack exchange,提问作者mimi_ra
相关产品推荐
相关产品推荐

