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

使用pyplot barbs绘制风矢图时出现尺寸不匹配错误

问题:Cartopy绘制风矢时X/Y尺寸不匹配错误

我有一个xarray.DataArray,想在Cartopy绘制的美国地图上,按均匀间隔的经纬度点绘制u、v风矢(barbs)。为了避免绘制所有点,我对风数据做了索引(比如每5个点取一个),但运行绘图时出现错误:

"X and Y must be the same size, but X.size is 45 and Y.size is 81."

基础代码如下:

data = 'VARIABLE'
data = data.sel(latitude=slice(latmax,latmin), longitude=slice(lonmin,lonmax))
lats = data['latitude']
lons = data['longitude']
u = u_array*10
v = v_array*10
plt.barbs(lats[::5],lons[::5],u,v)

u_wind数据示例:

xarray.DataArray'U_Wind'latitude: 45longitude: 401
array([[ 5.40691456e-03,  5.15891418e-03,  5.06325975e-03, ...,
         4.76794612e-03,  4.75683032e-03,  4.76837835e-03],
       [-1.43884958e-03, -1.18659466e-03, -8.66431906e-04, ...,
         4.50176722e-03,  4.41688955e-03,  4.33127597e-03],
       [ 1.62759619e-04,  5.66036437e-05, -6.58664997e-05, ...,
         4.82692387e-03,  4.81484310e-03,  4.59895644e-03],
       ...,
       [-2.11682637e-02, -2.12768081e-02, -2.13602273e-02, ...,
         1.28550304e-02,  1.25738495e-02,  1.23849878e-02],
       [-2.30783832e-02, -2.31578710e-02, -2.32645631e-02, ...,
         1.65182475e-02,  1.59745798e-02,  1.54944955e-02],
       [-2.58581950e-02, -2.59413023e-02, -2.60206995e-02, ...,
         1.88876221e-02,  1.89447670e-02,  1.90456638e-02]])

问题原因与解决方法

核心问题

你调用plt.barbs()的方式有误:

  • lats[::5]和lons[::5]是一维数组,长度分别为9(45/5)和81(401//5 +1),但plt.barbs()要求X、Y必须是与u、v同维度的二维网格坐标,而非单独的一维切片。同时,你没有对u、v做对应间隔的采样,导致风场维度和经纬度切片维度不匹配。

正确处理步骤

1. 同步采样经纬度与风场

必须对经纬度和u、v的两个维度(纬度、经度)做相同间隔的切片,保证采样后的数据维度完全一致。

2. 将一维经纬度转为二维网格

使用np.meshgrid把一维经纬度数组转换为二维网格,匹配风场的二维结构,这是barbs()函数要求的输入格式。

修改后的代码示例

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# 数据预处理
data = data.sel(latitude=slice(latmax, latmin), longitude=slice(lonmin, lonmax))
step = 5  # 采样间隔
# 对经纬度和风场同步采样
lats_sampled = data['latitude'][::step]
lons_sampled = data['longitude'][::step]
u_sampled = u_array[::step, ::step] * 10
v_sampled = v_array[::step, ::step] * 10

# 生成二维坐标网格
lon_grid, lat_grid = np.meshgrid(lons_sampled, lats_sampled)

# Cartopy绘图
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()  # 添加海岸线
# 绘制风矢,指定地理坐标转换
ax.barbs(lon_grid, lat_grid, u_sampled, v_sampled, transform=ccrs.PlateCarree())
plt.show()

关键说明

  • 采样时必须对u、v的两个维度都做[::step]切片,确保采样后风场的维度(比如(9,81))和经纬度网格的维度完全一致。
  • Cartopy绘图时必须指定transform=ccrs.PlateCarree()(假设你的经纬度是WGS84地理坐标),否则风矢会显示在错误的投影位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:23:15