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

如何将Cartopy等值面图改为纯色网格方格图?pcolormesh维度不兼容报错解决求助

Fixing Dimension Mismatch with pcolormesh in Cartopy

Let's break down why you're seeing that error and how to fix it.

Why the Error Happens

The pcolormesh function works differently than contourf:

  • contourf uses your grid centers (the lon/lat points you have) to interpolate and fill between them.
  • pcolormesh draws solid-colored squares, which requires defining the boundaries of each grid cell, not just the centers.

Your current lon2d and lat2d are grids of cell centers (shape (15,21)), matching your data df (also (15,21)). But pcolormesh expects the X/Y grids to be one dimension larger than your data: if your data is (M,N), the boundary grids need to be (M+1,N+1) to define the edges of each square.

How to Fix It

  1. Generate grid boundary arrays instead of just center points. For your existing ranges:

    • Longitude centers: np.arange(-15, -9.75, 0.25) → boundaries should start at -15, end at -9.75 + 0.25 = -9.5 (since each cell is 0.25 units wide)
    • Latitude centers: np.arange(6.5, 10.25, 0.25) → boundaries start at 6.5, end at 10.25 + 0.25 = 10.5
  2. Create the boundary grid with meshgrid, then pass these to pcolormesh.

Here's the modified code section:

# Generate boundary arrays instead of center-only arrays
lon_bounds = np.arange(-15, -9.5, 0.25)  # Now has 22 points (21 cells)
lat_bounds = np.arange(6.5, 10.5, 0.25)  # Now has 16 points (15 cells)

# Create 2D boundary grids
lon2d_bounds, lat2d_bounds = np.meshgrid(lon_bounds, lat_bounds)

# Set up the plot as before
plt.figure(figsize=(6,5))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([-15,-10,6.5,10])
ax.coastlines()
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.LAKES)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.BORDERS)
gl = ax.gridlines(draw_labels=True, xlocs=np.arange(-180,180,0.25), ylocs=np.arange(-90,90,0.25),linewidth=0.4)
gl.top_labels = False
gl.right_labels = False

# Now pcolormesh will work with matching dimensions
plot = plt.pcolormesh(lon2d_bounds, lat2d_bounds, df, cmap='jet', transform=ccrs.PlateCarree())

Quick Check

  • Your data df is (15,21) (15 latitude cells × 21 longitude cells)
  • The boundary grids lon2d_bounds and lat2d_bounds are (16,22) (16 latitude edges × 22 longitude edges)
  • This matches the requirement for pcolormesh: the X/Y grids define the corners of each data cell, so they need one extra point in each dimension.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:49:06