Geopandas 绘制形状并在形状外部应用不透明度

Goeopandas plot shape and apply opacity outside shape

我正在绘制一个城市边界(geopandas 数据框),我使用上下文向其添加了底图。 我想对城市范围以外的地图区域应用不透明度。 下面的示例显示了与预期效果相反的效果,因为不透明度应该应用于城市范围以外的所有地方。

import osmnx as ox
import geopandas as gpd
import contextily as cx

berlin = ox.geocode_to_gdf('Berlin,Germany')
fig, ax = plt.subplots(1, 1, figsize=(10,10))
_ = ax.axis('off')

berlin.plot(ax=ax,
            color='white',
            edgecolor='black',
            alpha=.7,
           )

# basemap 
cx.add_basemap(ax,crs=berlin.crs,)

plt.savefig('Whosebug_question.png',
            dpi=100,
            bbox_inches='tight',
           )

显示与期望结果相反的图:

您可以创建一个新的多边形,它是几何总边界减去几何的缓冲区

import osmnx as ox
import geopandas as gpd
import contextily as cx
import matplotlib.pyplot as plt
from shapely.geometry import box


berlin = ox.geocode_to_gdf("Berlin,Germany")
notberlin = gpd.GeoSeries(
    [
        box(*box(*berlin.total_bounds).buffer(0.1).bounds).difference(
            berlin["geometry"].values[0]
        )
    ],
    crs=berlin.crs,
)


fig, ax = plt.subplots(1, 1, figsize=(10, 10))
_ = ax.axis("off")

notberlin.plot(
    ax=ax,
    color="white",
    edgecolor="black",
    alpha=0.7,
)

# basemap
cx.add_basemap(
    ax,
    crs=berlin.crs,
)

# plt.savefig('Whosebug_question.png',
#             dpi=100,
#             bbox_inches='tight',
#            )