You need to enable JavaScript to run this app. 如何在R ggplot密度热图中仅保留指定MULTIPOLYGON范围内的区域
优惠活动
大模型
产品
解决方案
定价
更多

如何在R ggplot密度热图中仅保留指定MULTIPOLYGON范围内的区域

R ggplot 密度热图按MULTIPOLYGON裁剪实现方案

你可以通过以下两种常用方法实现仅展示多边形范围内的热图区域:

方法1:预先裁剪原始密度数据(推荐,性能更稳定)

先将密度数据转为空间sf对象,和目标MULTIPOLYGON做空间交集筛选,仅保留范围内的点再绘图:

# 加载依赖包
library(sf)
library(ggplot2)

# 1. 将原始海豚密度数据转为sf对象,和poly使用相同的WGS84坐标系
data_dolphins_sf <- st_as_sf(data.dolphins, coords = c("lon", "lat"), crs = st_crs(poly))

# 2. 筛选出仅落在poly范围内的观测点
data_dolphins_clipped <- st_intersection(data_dolphins_sf, poly)

# 3. 转回普通数据框适配geom_contour_fill的参数要求
data_dolphins_clipped_df <- cbind(
  st_drop_geometry(data_dolphins_clipped), 
  st_coordinates(data_dolphins_clipped)
) |> rename(lon = X, lat = Y)

# 4. 绘制裁剪后的热图
data_smoothed = ggplot() +
  metR::geom_contour_fill(
    data = data_dolphins_clipped_df, 
    aes(x = lon, y = lat, z = density), 
    bins = 120, na.fill = TRUE
  )+
  # 直接使用poly的边界作为绘图范围
  coord_sf(
    xlim = c(st_bbox(poly)$xmin, st_bbox(poly)$xmax), 
    ylim = c(st_bbox(poly)$ymin, st_bbox(poly)$ymax)
  )+
  scale_fill_viridis_c() +
  metR::scale_x_longitude(ticks = 2)+
  metR::scale_y_latitude(ticks=2)+
  # 可选:绘制多边形边界线,不需要可删除该行
  geom_sf(data = poly, fill = NA, color = "black", linewidth = 0.3)+
  theme_bw() +
  ggtitle("dolphins")+
  theme(plot.title = element_text(hjust = 0.5))

方法2:绘图层直接遮罩裁剪(无需修改原始数据)

使用ggfx包的遮罩功能直接对热图层做范围裁剪,适合不想改动原始数据集的场景:

# 先安装加载依赖包
# install.packages("ggfx")
library(ggfx)

data_smoothed = ggplot() +
  # 对热图层应用poly范围遮罩
  ggfx::with_mask(
    metR::geom_contour_fill(
      data = data.dolphins, 
      aes(x = lon, y = lat, z = density), 
      bins = 120, na.fill = TRUE
    ),
    mask = geom_sf(data = poly, fill = "white")
  )+
  coord_sf(
    xlim = c(st_bbox(poly)$xmin, st_bbox(poly)$xmax), 
    ylim = c(st_bbox(poly)$ymin, st_bbox(poly)$ymax)
  )+
  scale_fill_viridis_c() +
  metR::scale_x_longitude(ticks = 2)+
  metR::scale_y_latitude(ticks=2)+
  # 可选:绘制多边形边界线
  geom_sf(data = poly, fill = NA, color = "black", linewidth = 0.3)+
  theme_bw() +
  ggtitle("dolphins")+
  theme(plot.title = element_text(hjust = 0.5))

注意事项

操作前请确认data.dolphins的经纬度坐标系和poly的WGS84坐标系一致,避免空间匹配错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:39:03