如何在R语言中基于Shapefile创建英国六边形土地利用可视化地图
英国土地利用占比六边形网格地图实现方案
需求说明
- 创建英国境内的六边形网格地图
- 每个六边形的颜色仅对应英国整体土地利用类型的占比,与地理位置无关
- 无需点密度分箱,只需按固定比例分配不同颜色的六边形
实现代码
library("sf") library("tidyverse") library("rnaturalearth") library("rnaturalearthdata") library("scales") # 加载英国边界数据 uk <- ne_countries(scale = "large", country = "United Kingdom", returnclass = "sf") # 1. 生成英国境内的六边形网格(完整多边形) grid_spacing <- 0.3 hex_grid <- st_make_grid(uk, square = FALSE, cellsize = c(grid_spacing, grid_spacing * 0.5)) %>% st_sf() %>% st_intersection(uk) # 2. 按土地利用占比分配类型和颜色 # 虚拟土地利用类型及占比 land_use_types <- c("agriculture", "forestry", "urban", "other") land_use_props <- c(0.6, 0.2, 0.1, 0.1) land_use_cols <- viridis_pal()(length(land_use_types)) # 计算每种类型对应的六边形数量,补全总数差值 hex_counts <- floor(nrow(hex_grid) * land_use_props) hex_counts[length(hex_counts)] <- hex_counts[length(hex_counts)] + (nrow(hex_grid) - sum(hex_counts)) # 为网格分配类型与颜色 hex_grid <- hex_grid %>% mutate( land_use = rep(land_use_types, hex_counts), fill_color = rep(land_use_cols, hex_counts) ) # 3. 绘制六边形网格地图 ggplot() + geom_sf(data = hex_grid, aes(fill = fill_color), color = alpha("white", 0.7)) + scale_fill_identity(guide = "legend", labels = land_use_types) + labs(fill = "土地利用类型") + theme_void()
关键步骤说明
- 生成完整六边形网格:用
st_make_grid直接生成六边形多边形(而非中心点),再通过st_intersection裁剪出英国境内的部分,解决原代码用点模拟的问题 - 按比例分配颜色:根据设定的占比计算每种土地利用类型对应的六边形数量,直接绑定到网格数据上,确保整体比例符合需求,避开了
stat_summary_hex的密度分箱逻辑 - 可视化优化:用
geom_sf绘制多边形网格,通过scale_fill_identity保留自定义配色并添加图例,还原地图的直观性
内容的提问来源于stack exchange,提问作者DannyBON
相关产品推荐
相关产品推荐

