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

如何在ggplot2中实现等高线图仅显示于陆地区域?

解决方案:在ggplot2中仅陆地显示等高线

有两种可靠的方法实现需求,无需手动用PowerPoint处理:

方法一:裁剪数据至陆地区域(推荐,更高效)

先筛选出落在陆地上的概率数据点,再基于这些点绘制等高线,从根源避免海洋区域出现等高线。

代码示例

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

# 获取并裁剪目标区域的陆地多边形
world <- ne_countries(scale = "medium", returnclass = "sf")
world_clip <- st_crop(world, xmin = -2.3, xmax = 1.9, ymin = 50.9, ymax = 53.5)

# 将你的概率数据转换为sf空间对象(确保Lng是经度,Lat是纬度)
data_sf <- st_as_sf(data, coords = c("Lng", "Lat"), crs = st_crs(world))

# 仅保留落在陆地上的数据点
data_land <- st_intersection(data_sf, world_clip)

# 提取经纬度数值列(供geom_contour使用)
data_land <- data_land %>%
  mutate(Lng = st_coordinates(.)[,1],
         Lat = st_coordinates(.)[,2])

# 绘制最终地图
ggplot() +
  geom_sf(data = world_clip, color = "black", fill = "gray") +
  geom_contour(data = data_land, aes(x = Lng, y = Lat, z = P), bins = 20) +
  coord_sf(xlim = c(-2.3, 1.9), ylim = c(50.9, 53.5), expand = FALSE)

方法二:用海洋遮罩覆盖等高线

若不想修改原始数据,可创建海洋区域的多边形,将其填充为黑色(或背景色)覆盖在等高线之上,隐藏海洋部分的线条。

代码示例

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

# 获取并裁剪陆地多边形
world <- ne_countries(scale = "medium", returnclass = "sf")
world_clip <- st_crop(world, xmin = -2.3, xmax = 1.9, ymin = 50.9, ymax = 53.5)

# 创建目标区域的边界多边形
bbox_sf <- st_sfc(st_polygon(list(rbind(
  c(-2.3, 50.9), c(1.9, 50.9), c(1.9, 53.5), c(-2.3, 53.5), c(-2.3, 50.9)
))), crs = st_crs(world))

# 计算海洋区域:边界减去陆地
ocean_sf <- st_difference(bbox_sf, st_union(world_clip))

# 绘制地图(注意图层顺序:等高线→陆地→海洋遮罩)
ggplot() +
  geom_contour(data = data, aes(x = Lng, y = Lat, z = P), bins = 20) +
  geom_sf(data = world_clip, color = "black", fill = "gray") +
  geom_sf(data = ocean_sf, fill = "black", color = NA) +
  coord_sf(xlim = c(-2.3, 1.9), ylim = c(50.9, 53.5), expand = FALSE)

关于你遇到的错误

Error: Attempted to create layer with no position. 通常是因为混用geom_sf(基于空间几何列)和geom_contour(基于数值型x/y列)时,坐标系统不一致或图层数据格式不匹配。上述两种方法都通过统一空间处理或明确数据格式解决了这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:55:12