matplotlib 更新面片边界以排除具有制图的土地

sc4hvdpw  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(148)

快速但可能很难的问题:我已经画了一张Map,其中包括一个在大西洋东部的方框,使用matplotlib补丁创建。我希望改变方框的形状,这样唯一包括的区域是海洋-本质上,我想掩盖非洲和欧洲,这样他们仍然出现,但我的方框不包括陆地。这是我目前拥有的图像。

它是用以下代码绘制的:

ax.set_extent([5, -150, 0, 80], crs=ccrs.PlateCarree())
ax.add_feature(cartopy.feature.OCEAN, zorder=0)
ax.add_feature(cartopy.feature.LAND, zorder=0, edgecolor='black')
gl = ax.gridlines(draw_labels=True, linewidth=0.5, alpha=0.4, color='k',
                  linestyle='--')
ax.add_patch(mpatches.Rectangle(xy=[-30, 20], width=25, height=30,
                                facecolor='none', edgecolor='r',
                                linewidth=2,
                                transform=ccrs.PlateCarree()))

而这样的东西正是我想要的。

这在Cartopy中可能吗?

ecfsfe2w

ecfsfe2w1#

是的,这道题很难。不过,我设法得到了一个应该被认为是好的结果。

import numpy as np, geopandas as gpd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
#from matplotlib import patches as mpatches
from shapely.geometry import Polygon

# Get world coastlines as a geo dataframe `gdf1`
gdf1 = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
gdf1 = gdf1.dissolve()  # dissolve into 1 geometry
world_landmass = gdf1.geometry[0]  # get the geometry

# Define the CRS for plotting
# Try: ccrs.PlateCarree(), ccrs.Robinson()
use_proj = ccrs.PlateCarree()
fig, ax = plt.subplots(figsize=(4,4), subplot_kw=dict(projection=use_proj))

ax.set_extent([-35, 0, 15, 55], crs=ccrs.PlateCarree())
ax.add_feature(cartopy.feature.OCEAN, zorder=0)
ax.add_feature(cartopy.feature.LAND, zorder=0, edgecolor='black')

# Draw gridlines
gl = ax.gridlines(draw_labels=True, linewidth=0.5, alpha=0.4, color='k',
                  linestyle='--')

# Create the rectangle shape
# I use Polygon object, so that, it can be spatially manipulated easily
x0, y0 = -30, 20
w, h = 25, 30
rect = Polygon([(x0, y0), (x0, y0+h), (x0+w, y0+h), (x0+w, y0)])

# Spatially subtract the rectangle by the land_mass
poly_cut = rect.difference(world_landmass)

# Add the result to the plot
# Use fc="none" to get transparent areas
ax.add_geometries([poly_cut], fc="white", ec='red', alpha=0.7, lw=5, crs=ccrs.PlateCarree())

如果使用use_proj = ccrs.Robinson(),则出图为。

相关问题