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

如何在Matplotlib绘制的Contour Plot上添加各点数值?

在WRF/Matplotlib等值线图上标注数据点数值

要在你现有的等值线图基础上给每个数据点标注数值,可以通过遍历经纬度和对应变量值,使用ax.text()方法添加文本实现,具体步骤如下:

关键修改步骤

  1. 将WRF变量转换为NumPy数组,方便后续遍历操作
  2. 嵌套循环遍历每个网格点,在对应经纬度位置添加数值标注
  3. 根据需求调整标注的字体大小、颜色等样式,避免文字重叠

修改后的完整代码

from matplotlib.cm import get_cmap
import numpy as np
from cartopy import crs
from cartopy.feature import NaturalEarthFeature
import matplotlib
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import xarray as xr

from wrf import (getvar, interplevel, vertcross, 
                 CoordPair, ALL_TIMES, to_np,
                 get_cartopy, latlon_coords,
                 cartopy_xlim, cartopy_ylim)


lats, lons = latlon_coords(ctt)
cart_proj = get_cartopy(ctt)

# 将变量转换为NumPy数组,便于遍历
ctt_data = to_np(ctt)
lats_np = to_np(lats)
lons_np = to_np(lons)

fig = plt.figure(figsize=(12,9))
ax_ctt = fig.add_subplot(1,1,1,projection=cart_proj)

contour_levels = [-10, 0, 10, 20, 30, 40]
ctt_contours = ax_ctt.contourf(lons_np, lats_np, ctt_data,
                               contour_levels, cmap=get_cmap("Blues_r"),
                               transform=crs.PlateCarree())

# 添加数据点数值标注
# 若网格点过密,可修改循环步长(如range(0, lats_np.shape[0], 2))减少标注数量
for i in range(lats_np.shape[0]):
    for j in range(lats_np.shape[1]):
        val = round(ctt_data[i, j], 1)  # 保留1位小数,提升可读性
        ax_ctt.text(lons_np[i, j], lats_np[i, j], str(val),
                    transform=crs.PlateCarree(),
                    fontsize=8,
                    color='black',
                    ha='center', va='center')

cb_ctt = fig.colorbar(ctt_contours, ax=ax_ctt, shrink=.60)
cb_ctt.ax.tick_params(labelsize=9)

ax_ctt.set_xlim(cartopy_xlim(ctt))
ax_ctt.set_ylim(cartopy_ylim(ctt))
ax_ctt.gridlines(color="white", linestyle="dotted")

states = NaturalEarthFeature(category="cultural", scale="10m",
                             facecolor="none",
                             name="admin_1_states_provinces")
ax_ctt.add_feature(states, linewidth=0.2, edgecolor="black")
ax_ctt.coastlines('10m', linewidth=0.4)

plt.show()

注意事项

  • 避免标注重叠:如果网格分辨率较高,全量标注会导致文字重叠,可通过调整循环步长(比如range(0, lats_np.shape[0], 2))实现间隔标注
  • 样式自定义:可以修改fontsize调整字体大小,color修改标注颜色,ha(水平对齐)和va(垂直对齐)确保文字居中在数据点上
  • 坐标转换:必须指定transform=crs.PlateCarree(),因为经纬度数据属于地理坐标系,需要匹配Cartopy的投影转换规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:14:56