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

如何在ggplot中使用geom_sf裁剪geom_tiles几何对象?

用geom_sf裁剪geom_tile的两种方法

你可以通过提前过滤数据或者图层遮罩两种方式,让国家边界外的拟合值不显示,以下是具体实现:

方法1:提前筛选边界内的网格数据(推荐)

先把gam拟合数据转换成空间对象,筛选出国家边界内的网格点后再绘制tile:

library(ggplot2)
library(sf)

# 修正原代码问题:需加载ggplot2而非ggplot,且末尾多一个闭合括号
# 1. 将gam数据转为sf点对象,确保与country的坐标系一致
gam_sf <- st_as_sf(gam, coords = c("longitude", "latitude"), crs = st_crs(country))

# 2. 筛选出落在国家边界内的点
gam_inside <- gam_sf[st_within(gam_sf, country, sparse = FALSE), ]

# 3. 转回普通数据框(geom_tile需要x、y列)
gam_filtered <- st_drop_geometry(gam_inside)

# 4. 绘图
ggplot() +
  geom_tile(data = gam_filtered, aes(x = longitude, y = latitude, fill = .fitted)) +
  geom_sf(data = country, fill = NA, color = "black")

注意:如果gam和country的坐标系(CRS)不一致,先用st_transform(country, crs = st_crs(gam_sf))统一坐标系

方法2:用ggfx包做实时图层遮罩

不想修改原始数据的话,可借助ggfx的遮罩功能,直接隐藏边界外的tile:

library(ggplot2)
library(sf)
library(ggfx)

ggplot() +
  # 用国家边界作为遮罩,仅显示范围内的tile
  with_mask(
    geom_tile(data = gam, aes(x = longitude, y = latitude, fill = .fitted)),
    mask = geom_sf(data = country, fill = "white")
  ) +
  # 叠加国家边界线
  geom_sf(data = country, fill = NA, color = "black")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:03:18