Cartopy 系列:裁剪填色图出界问题
前言
裁剪或者说白化,就是让填色图只显示在多边形里面,不显示在多边形外面,例如只显示 GeoAxes.contourf
在中国境内的结果。实现方法为:
from matplotlib.path import Path
from cartopy.mpl.patch import geos_to_path
from cartopy.io.shapereader import Reader
reader = Reader(filepath)
geom = next(reader.geometries())
reader.close()
cf = ax.contourf(X, Y, Z, transform=crs)
geom = ax.projection.project_geometry(geom, crs)
path = Path.make_compound_path(*geos_to_path(geom))
for col in cf.collections:
col.set_clip_path(path, ax.transData)
- 将
crs
坐标系上的多边形对象变换到 data 坐标系上。 - 利用
geos_to_path
和make_compound_path
将变换后的多边形转为Path
对象。 - 对
QuadContourSet.collections
里的每个成员调用set_clip_path
方法,并且指定 data 坐标系。