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

Python绘制北海盐度地图时如何在网格点上添加数据标签?

北海区域盐度地图网格点数值标注实现方案

以下是可直接运行的实现代码,兼容你提供的模拟数据与真实业务数据:

import xarray as xa
import numpy as np
import matplotlib.pyplot as plt
import cmocean.cm as cm
import cartopy.crs as ccrs
import cartopy.feature as cfeat

# ---------------------- 数据准备 ----------------------
# 下方为模拟数据代码,使用真实数据时直接删除即可,替换为你之前处理好的salt_ocean变量
data = 15 + 8 * np.random.randn(8, 8)
lons = np.linspace(-13, 16, 8)
lats = np.linspace(50, 65, 8)
salt_ocean = xa.DataArray(data, coords=[lats, lons], dims=['latitude', 'longitude'])

# ---------------------- 绘图逻辑 ----------------------
# 创建带地理投影的画布
fig, ax = plt.subplots(figsize=(10, 8), subplot_kw={'projection': ccrs.PlateCarree()})
# 限定北海区域显示范围
ax.set_extent([-13, 16, 50, 65], crs=ccrs.PlateCarree())
# 添加基础地图要素
ax.add_feature(cfeat.LAND.with_scale('10m'), facecolor='lightgray')
ax.add_feature(cfeat.COASTLINE.with_scale('10m'), linewidth=0.8)
ax.add_feature(cfeat.BORDERS.with_scale('10m'), linestyle=':', linewidth=0.5)

# 绘制盐度热力底图
salt_ocean.plot(
    ax=ax, 
    transform=ccrs.PlateCarree(), 
    cmap=cm.haline, 
    cbar_kwargs={'label': '盐度'}
)

# 遍历网格点添加数值标注
for lon in salt_ocean.longitude.values:
    for lat in salt_ocean.latitude.values:
        sal_val = salt_ocean.sel(longitude=lon, latitude=lat).values
        # 自动跳过空值不标注
        if np.isfinite(sal_val):
            # 标注位置与样式可按需调整
            ax.text(
                lon, lat, f'{sal_val:.1f}', 
                transform=ccrs.PlateCarree(),
                ha='center',
                va='bottom',
                fontsize=9,
                color='black'
            )

# 添加可显示标签的经纬度网格
grid = ax.gridlines(
    crs=ccrs.PlateCarree(), draw_labels=True,
    linewidth=0.5, color='gray', alpha=0.5, linestyle='--'
)
grid.top_labels = False
grid.right_labels = False

plt.title('北海区域深度&时间平均盐度分布')
plt.show()

可调参数说明

  • 数值精度:将f'{sal_val:.1f}'中的.1f修改为.2f即可保留2位小数,按需调整即可
  • 标注位置:如果需要标注和网格点拉开距离,可将lat参数替换为lat + 0.15,偏移量根据显示效果调整
  • 文本样式:修改fontsize调整字号,color参数可改为白色适配深色底图,避免文字看不清
  • 地图性能:如果绘图速度慢,可将地图要素的'10m'分辨率改为'50m',不需要的要素可直接删除对应代码行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:12:01