cartopy
cartopy copied to clipboard
Apply set_clip_path to contours, but the set_extend is not work.
Hi: I want to clip the contours with shapefile. But with setting the map extent, the figure failed to zoom the region limit. So why? The code is :
def crsmask(shpfilename, region, ax, crs, conf, pathkw = None):
import cartopy.io.shapereader as shpreader
from cartopy.mpl.patch import geos_to_path
from matplotlib.patches import PathPatch
reader = shpreader.Reader(shpfilename)
countries = reader.records()
try:
multipoly, = [country.geometry for country in countries
if country.attributes['name'] == region]
except KeyError:
multipoly, = [country.geometry for country in countries
if country.attributes['NAME'] == region]
main_geom = sorted(multipoly.geoms, key=lambda geom: geom.area)[-1]
path, = geos_to_path(main_geom)
plate_carre_data_transform = crs._as_mpl_transform(ax)
for collection in conf.collections:
collection.set_clip_path(path, plate_carre_data_transform)
return path
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
from cartopy.examples.waves import sample_data
# subplot_kw
fig, ax = plt.subplots(subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([103., 113, 20, 27.], crs=ccrs.PlateCarree())
plate_carre_data_transform = ccrs.PlateCarree()._as_mpl_transform(ax)
lons, lats, data = sample_data()
con = ax.contourf(lons, lats, data, transform=ccrs.PlateCarree())
shpfilename = shpreader.natural_earth(resolution='10m',
category='cultural',
name='admin_0_countries')
# clip the shapefile polygon
path = crsmask(shpfilename, 'China', ax, ccrs.PlateCarree(), con)
plt.show()
I think this is because contourf is calling autoscale to readjust the limits after you've set the extent. What happens if you move the ax.set_extent() call just before the show (after the contourf call).
I think this is because
contourfis calling autoscale to readjust the limits after you've set the extent. What happens if you move theax.set_extent()call just before the show (after the contourf call).
Hi, greglucas: It's still not work if I 'ax.set_extent' called before the show.
代主任,可以对每一个被裁切的图元artist,除了进行set_clip_path之外,也要进行set_clip_box(ax.bbox) 或者set(clip_box=ax.bbox),就可以了 For each artist which should be clipped,add artist.set(clip_box=ax.bbox). 可见视频8:30左右 https://www.bilibili.com/video/BV1Ao4y1N7K8/?spm_id_from=pageDriver&vd_source=4753b17af2eaebe245ddf00b73157cf1