使用Cartopy绘制Xarray pcolormesh时出现TypeError错误
Yep, I’ve encountered this exact compatibility issue before with the package versions you’re using—let’s walk through why it happens and how to resolve it quickly.
Why This Error Occurs
This is a version mismatch between Cartopy 0.17.0 and Matplotlib 3.3.0. Cartopy 0.17.0’s implementation of pcolormesh passes an allmatch argument to Matplotlib’s underlying _pcolorargs() function, but Matplotlib 3.3.0 doesn’t support this parameter yet. The two packages just aren’t aligned here.
Solutions to Try
1. Upgrade Cartopy to 0.18.0+ (Recommended)
Cartopy 0.18.0 fixed this compatibility issue by removing the allmatch parameter that was causing the conflict. This is the cleanest long-term fix.
To upgrade with pip:
pip install --upgrade cartopy>=0.18.0
If you’re using Conda, use the conda-forge channel (Cartopy’s official distribution channel):
conda install -c conda-forge cartopy>=0.18.0
2. Downgrade Matplotlib to 3.2.x
If upgrading Cartopy isn’t an option right now, downgrading Matplotlib to a version that doesn’t mind the allmatch argument (like 3.2.2) will also resolve the error.
With pip:
pip install matplotlib==3.2.2
With Conda:
conda install matplotlib=3.2.2
3. Manual Coordinate Transformation (No Version Changes)
If you can’t modify your package versions, you can bypass Cartopy’s pcolormesh wrapper by manually transforming your coordinates to the target projection first:
import matplotlib.pyplot as plt import cartopy.crs as ccrs import numpy as np # Create a meshgrid of your lat/lon coordinates lons, lats = np.meshgrid(da.lon, da.lat) # Transform coordinates to Mollweide projection target_crs = ccrs.Mollweide() x, y = target_crs.transform_points(ccrs.PlateCarree(), lons, lats).T # Plot with native Matplotlib pcolormesh fig, ax = plt.subplots(subplot_kw={'projection': target_crs}) ax.pcolormesh(x, y, da.values) ax.coastlines() # Add coastlines for context plt.show()
Bonus: Try Xarray’s Built-in Plotting
You could also test using Xarray’s own plot.pcolormesh method, which handles some of the projection logic internally and might avoid the conflict:
import matplotlib.pyplot as plt import cartopy.crs as ccrs fig, ax = plt.subplots(subplot_kw={'projection': ccrs.Mollweide()}) da.plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree()) ax.coastlines() plt.show()
内容的提问来源于stack exchange,提问作者Andrew Williams

