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

如何使用marmap的stat_contour()填充水深区域?附ggplot2绘制代码

用stat_contour()填充水深区域的解决方案

嘿,你已经把水深数据处理成了ggplot兼容的长格式数据框,这一步走得很对!接下来咱们直接用stat_contour()来实现填充区域的效果,我给你一步步拆解:

完整代码示例

基于你已经处理好的Bathydf,直接运行下面的代码就能得到填充好的水深图:

library(ggplot2)
library(dplyr)
library(tidyr)
library(marmap)

# 你的数据预处理代码(已完成)
Bathy <- getNOAA.bathy(lon1 = 37, lon2 = 38.7, lat1 = -45.5, lat2 = -47.3, resolution = 1)
Bathy <- as.matrix(Bathy)
class(Bathy) <- "matrix"
Bathydf <- as.data.frame(Bathy)
Bathydf <- rownames_to_column(Bathydf, var = "Longitude")
Bathydf <- gather(Bathydf, Latitude, Depth, -1)
Bathydf <- mutate_all(Bathydf, as.numeric)

# 核心绘图代码:用stat_contour填充水深
ggplot(Bathydf, aes(x = Longitude, y = Latitude, z = Depth)) +
  # 关键:用stat_contour生成填充多边形,映射fill到计算出的等高线level
  stat_contour(aes(fill = after_stat(level)), geom = "polygon") +
  # 设置配色:水深越深(数值越小)颜色越深,这里用viridis配色更友好
  scale_fill_viridis_c(option = "viridis", direction = -1, name = "水深(m)") +
  # 添加海岸线(0米线),区分海陆
  stat_contour(breaks = 0, color = "black", size = 1) +
  # 调整标签和布局
  labs(x = "经度", y = "纬度", title = "西南印度洋区域水深填充图") +
  coord_fixed() # 必须加!保持经纬度比例,避免地图变形

关键参数解释

  • geom = "polygon":告诉stat_contour()不要只画线条,而是把等高线之间的区域绘制成多边形并填充;
  • after_stat(level):stat_contour()会自动计算等高线的数值(也就是水深值),用after_stat()可以获取这个计算结果,把它映射到填充颜色上;
  • scale_fill_viridis_c:用连续型的viridis配色,direction = -1是因为NOAA的水深数据里,水下深度是负数(数值越小代表越深),这样设置能让更深的区域显示更深的颜色;
  • coord_fixed():经纬度地图必须保持比例一致,否则会被拉伸变形,这个参数能帮你锁定正确的比例。

更简洁的替代方案:geom_contour_filled()

如果你觉得上面的写法有点繁琐,也可以用geom_contour_filled()——它其实是stat_contour(geom = "polygon")的封装,代码更简洁:

ggplot(Bathydf, aes(x = Longitude, y = Latitude, z = Depth)) +
  geom_contour_filled(aes(fill = after_stat(level))) +
  # 注意这里用离散型配色,因为geom_contour_filled会把等高线分成离散区间
  scale_fill_viridis_d(option = "viridis", direction = -1, name = "水深(m)") +
  stat_contour(breaks = 0, color = "black", size = 1) +
  labs(x = "经度", y = "纬度", title = "西南印度洋区域水深填充图") +
  coord_fixed()

实用小技巧

  • 自定义等高线间隔:如果想每500米画一条等高线,可以在stat_contour()里添加breaks = seq(-6000, 0, by = 500)(数值范围根据你的目标区域实际水深调整);
  • 仅展示水下区域:提前过滤数据,去掉陆地部分:Bathydf <- filter(Bathydf, Depth < 0);
  • 优化绘图速度:resolution = 1会生成超大数据集,可适当调大分辨率数值(比如5)来加快绘图效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:01:49