我想绘制来自全局多维数据集的数据,但仅限于国家/地区列表。因此,我根据国家/地区的“边界框”选择一个子立方体。
到目前为止一切顺利。我正在寻找一种简单的方法来掩盖立方体中不属于我的任何国家/地区的所有点(这些点表示为特征),以便只有位于我的任何特征内的立方体的那些点已绘制。
任何想法都将不胜感激 =)
最佳答案
您可以直接在绘图阶段实现此目的,而不是在虹膜内遮盖立方体。我通过设置 pcolor
返回的艺术家的剪辑路径来解决这个问题。该方法是根据要素创建几何图形列表(在本例中是来自自然地球的国家,它们可能来自 shapefile),然后将这些几何图形转换为可以将图像剪切到的 matplotlib 路径。我将详细介绍此方法,希望这足以帮助您入门:
我首先定义了一个函数来检索给定国家名称对应的Shapely几何图形,这些几何图形来自Natural Earth 110m行政边界shapefile,通过cartopy接口(interface)访问。
然后我定义了第二个函数,它是 iris.plot.pcolor
的包装器。绘制绘图并将其裁剪为给定几何形状的函数。
现在我需要做的就是像平常一样设置绘图,但使用绘图包装器而不是直接调用 iris.plot.pcolor
功能。
这是一个完整的示例:
import cartopy.crs as ccrs
from cartopy.io.shapereader import natural_earth, Reader
from cartopy.mpl.patch import geos_to_path
import iris
import iris.plot as iplt
import matplotlib.pyplot as plt
from matplotlib.path import Path
def get_geometries(country_names):
"""
Get an iterable of Shapely geometries corrresponding to given countries.
"""
# Using the Natural Earth feature interface provided by cartopy.
# You could use a different source, all you need is the geometries.
shape_records = Reader(natural_earth(resolution='110m',
category='cultural',
name='admin_0_countries')).records()
geoms = []
for country in shape_records:
if country.attributes['name_long'] in country_names:
try:
geoms += country.geometry
except TypeError:
geoms.append(country.geometry)
return geoms, ccrs.PlateCarree()._as_mpl_transform
def pcolor_mask_geoms(cube, geoms, transform):
path = Path.make_compound_path(*geos_to_path(geoms))
im = iplt.pcolor(cube)
im.set_clip_path(path, transform=transform)
# First plot the full map:
cube = iris.load_cube(iris.sample_data_path('air_temp.pp'))
plt.figure(figsize=(12, 6))
ax1 = plt.axes(projection=ccrs.PlateCarree())
ax1.coastlines()
iplt.pcolor(cube)
# Now plot just the required countries:
plt.figure(figsize=(12, 6))
ax2 = plt.axes(projection=ccrs.PlateCarree())
ax2.coastlines()
countries = [
'United States',
'United Kingdom',
'Saudi Arabia',
'South Africa',
'Nigeria']
geoms, transform = get_geometries(countries)
pcolor_mask_geoms(cube, geoms, transform(ax2))
plt.show()
其结果如下所示:
如果您想使用iris.plot.pcolormesh
相反,您需要稍微修改绘图函数。这是由于 cartopy 中当前包含的 matplotlib 问题的解决方法所致。修改后的版本将如下所示:
def pcolor_mask_geoms(cube, geoms, transform):
path = Path.make_compound_path(*geos_to_path(geoms))
im = iplt.pcolormesh(cube)
im.set_clip_path(path, transform=transform)
try:
im._wrapped_collection_fix.set_clip_path(path, transform)
except AttributeError:
pass
关于cartopy - 具有特征的面具立方体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27151614/