You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在geom_sf()绘图中添加点并按点数量为NUTS子单元着色?

欧洲NUTS2地图添加点及按点数量着色解决方案

一、添加单个点到地图

首先将普通坐标数据转换为sf空间对象,确保和地图坐标系匹配,再通过geom_sf添加:

  1. 加载所需包并转换点数据
library(eurostat)
library(sf)
library(ggplot2)
library(tibble)
library(dplyr)

# 你的点数据
df_points <- tibble(lat=c(40, 45, 50), lon=c(-1,  0, 10))

# 转换为sf格式,指定WGS84坐标系(EPSG:4326)
sf_points <- st_as_sf(df_points, coords = c("lon", "lat"), crs = 4326)
  1. 在原地图代码中添加点
SHP_0 %>% 
  ggplot() + 
  geom_sf() +
  # 添加点,可自定义样式
  geom_sf(data = sf_points, color = "darkred", size = 3, shape = 19) +
  scale_x_continuous(limits = c(-15, 40), labels = function(x) paste0(x, '°', "E")) +
  scale_y_continuous(limits = c( 35, 75), labels = function(x) paste0(x, '°', "N")) +
  theme(panel.background = element_rect(fill = "#42BFED", colour = "#42BFED"))

二、按NUTS2单元内点数量为多边形着色

核心是通过空间连接匹配点与多边形,统计数量后合并到地图数据:

  1. 空间连接并统计点数量
# 将每个点匹配到对应的NUTS2单元
point_nuts_match <- st_join(sf_points, SHP_0, join = st_within)

# 统计每个NUTS_ID的点数量,无点的单元设为0
point_count <- point_nuts_match %>%
  st_drop_geometry() %>%  # 移除空间属性以简化统计
  count(NUTS_ID, name = "point_count") %>%
  tidyr::replace_na(list(point_count = 0))

# 合并统计结果到原多边形数据
SHP_0_count <- SHP_0 %>%
  left_join(point_count, by = "NUTS_ID") %>%
  mutate(point_count = ifelse(is.na(point_count), 0, point_count))
  1. 绘制带着色的地图(同时保留点)
SHP_0_count %>% 
  ggplot() + 
  # 多边形按点数量着色
  geom_sf(aes(fill = point_count)) +
  # 添加点层,置于多边形上方
  geom_sf(data = sf_points, color = "white", size = 2, shape = 19) +
  # 设置填充色标,可自定义配色
  scale_fill_viridis_c(name = "单元内点数量", option = "magma") +
  scale_x_continuous(limits = c(-15, 40), labels = function(x) paste0(x, '°', "E")) +
  scale_y_continuous(limits = c( 35, 75), labels = function(x) paste0(x, '°', "N")) +
  theme(panel.background = element_rect(fill = "#42BFED", colour = "#42BFED"))

注意事项

  • 空间连接用st_within确保点完全处于多边形内部,若需包含边界相交的点,可替换为st_intersects。
  • 大数据集下,可通过st_simplify(SHP_0, dTolerance = 1000)简化多边形(单位:米)提升处理速度。
  • 点的样式参数(color/size/shape)可根据可视化需求调整,避免与填充色冲突。

内容的提问来源于stack exchange,提问作者Ivo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:20:53