如何在R语言中根据数据行数为地图上的国家着色?
问题描述
我们关注的wheels数据集如下:
wheels name country 1 The Southern Star Australia 2 Wheel of Brisbane Australia 3 Wheel of Perth Australia 4 Wiener Riesenrad Austria 5 Niagara SkyWheel Canada 6 Beijing Great Wheel China 7 Changsha Ferris Wheel China
如何在以下地图代码中,根据每个国家在wheels中的数据行数为国家着色?原绘图代码如下:
library(tidyverse); library(maptools); library(sf) # 主数据 wheels <- readr::read_csv("wheels.csv") # 数据源为TidyTuesday 2022-08-09数据集 # 地图数据 world <- map_data("world") data(wrld_simpl) countries <- st_as_sf(wrld_simpl) # 绘图 df_plot <- right_join(wheels, countries, by = c("country" = "NAME")) ggplot(df_plot, aes(LON, LAT)) + geom_map(data = world, map = world, aes(long, lat, map_id = region), color = "white", fill = "#66BBBB", size = 0.1)
是否需要用dplyr::count这类工具汇总数据?
补充编辑
我已经生成了统计wheels中各国数据行数的数据框:
# 按国家统计行数 data_count <- wheels %>% count(country) # 合并数据框 df_plot <- right_join(wheels, countries, by = c("country" = "NAME")) %>% left_join(data_count)
解决方案
是的,必须通过dplyr::count先汇总每个国家的记录数(即摩天轮数量),再将汇总结果与地图数据关联,才能实现按数量着色。你的汇总步骤方向正确,但存在重复数据关联的问题,以下是修正后的完整流程:
1. 正确汇总并关联数据
无需先将wheels与countries关联(会产生重复行),直接把统计结果和地图数据关联即可:
# 按国家统计摩天轮数量,重命名列名更直观 data_count <- wheels %>% count(country, name = "wheel_count") # 将统计结果与sf格式的国家地图数据关联 map_data_with_count <- left_join(countries, data_count, by = c("NAME" = "country"))
2. 使用sf对象绘制着色地图
既然已经用st_as_sf()转换了地图数据,推荐用geom_sf()绘图,逻辑更清晰:
ggplot() + # 绘制基础底图:未统计到摩天轮的国家用灰色填充 geom_sf(data = countries, fill = "gray80", color = "white", size = 0.1) + # 绘制有摩天轮的国家,按数量映射填充色 geom_sf(data = map_data_with_count %>% filter(!is.na(wheel_count)), aes(fill = wheel_count), color = "white", size = 0.1) + # 设置颜色渐变刻度,适配数据范围 scale_fill_viridis_c(option = "plasma", na.value = "gray80") + # 添加标题和图例标签 labs(title = "各国摩天轮数量分布", fill = "数量") + # 简化主题 theme_minimal()
3. 若坚持使用原代码的geom_map
需确保每个国家只对应一个统计值,避免重复行干扰:
# 将统计结果与world地图数据关联 world_with_count <- world %>% left_join(data_count, by = c("region" = "country")) ggplot() + geom_map(data = world_with_count, map = world_with_count, aes(map_id = region, fill = wheel_count), color = "white", size = 0.1) + # 适配地图范围 expand_limits(x = world$long, y = world$lat) + # 设置填充色 scale_fill_viridis_c(option = "plasma", na.value = "#66BBBB") + labs(title = "各国摩天轮数量分布", fill = "数量") + theme_minimal()
内容的提问来源于stack exchange,提问作者Julien
相关产品推荐
相关产品推荐

