I'm using Cartopy for my polar research and would like to clip a circular boundary around my data, which I plot in the NorthPolarStereo()
projection. I use set_extent
to indicate from what latitude I would like to plot my data and use set_boundary
for creating a circular boundary as explained in the gallery. I then use matplotlib.pyplot.pcolormesh
to plot the actual data. However, say I use set_extent
to define a minimum latitude of 55 degrees, some of my data below 55 degrees is still being plotted outside of my set_boundary
. How do I clip off this data?
map_crs = ccrs.NorthPolarStereo(central_longitude=0.0, globe=None)
# Build axes
fig = plt.figure()
ax = plt.axes(projection=map_crs)
plotfield = ax.pcolormesh(lons, lats, data, transform=ccrs.PlateCarree())
ax.set_extent((-180, 180, 55, 90), crs=ccrs.PlateCarree())
gl = ax.gridlines()
# Circular clipping
theta = np.linspace(0, 2*np.pi, 400)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
ax.set_boundary(circle, transform=ax.transAxes)
I don't have cartopy to test it in the same conditions as you, but you can clip a pcolormesh using a Patch object of any shape:
# the code below is adapted from the pcolormesh example
# https://matplotlib.org/3.1.0/gallery/images_contours_and_fields/pcolormesh_levels.html#sphx-glr-gallery-images-contours-and-fields-pcolormesh-levels-py
# make these smaller to increase the resolution
dx, dy = 0.05, 0.05
# generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(1, 5 + dy, dy),
slice(1, 5 + dx, dx)]
z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)
theta = np.linspace(0, 2*np.pi, 400)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = matplotlib.path.Path(verts * radius + center)
fig, ax = plt.subplots()
im = ax.pcolormesh(x, y, z, cmap='viridis', clip_path=(circle, ax.transAxes))
fig.colorbar(im, ax=ax)
fig.tight_layout()
plt.show()