如何将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:
contourfuses your grid centers (the lon/lat points you have) to interpolate and fill between them.pcolormeshdraws 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
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 at6.5, end at10.25 + 0.25 = 10.5
- Longitude centers:
Create the boundary grid with
meshgrid, then pass these topcolormesh.
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
dfis(15,21)(15 latitude cells × 21 longitude cells) - The boundary grids
lon2d_boundsandlat2d_boundsare(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
相关产品推荐
相关产品推荐

