Skip to main content
 首页 » 编程设计

python之更新 Geopandas 图中的补丁边缘颜色

2025年02月15日9duanxz

我使用以下代码(geopandas 0.2.1,matplotlib 2.0.2,在 Jupyter 笔记本中,使用 %inline)将 GeoDataFrame 绘制为等值线:

fig, ax = plt.subplots( 
    1, 
    figsize=(16., 12.), 
    dpi=100, 
    subplot_kw=dict(aspect='equal'), 
) 
 
base = imd_gdf.dropna().plot( 
    ax=ax, 
    alpha=1., 
    column="Rental_Count", 
    scheme="fisher_jenks", 
    k=7, 
    cmap="viridis", 
    linewidth=0.1, 
    edgecolor='black', 
    legend=True, 
) 

这给了我一张多边形周围有边的 map :

我想删除这些。到目前为止,我已经尝试循环遍历补丁,将边缘颜色设置为面部颜色:

for p in ax.patches: 
    nc = p.get_facecolor() 
    p.set_edgecolor(nc)  

但它没有任何效果,即使我在循环中指定了单一颜色。 p.set_color(nc) 或尝试使用 p.set_linewidth(0.0) 将线宽设置为 0 都没有任何效果。 我在这里错过了什么?使用 p.set_facecolor('white') 以相同的方式更新面部颜色效果很好:

请您参考如下方法:

结果是 plot() 绘制了一组线对象(AxesSubplot 的 lines 属性,它们是 lines.Line2D) 表示实际的边。如果您想完全控制边缘外观,则有必要更新这些以及补丁的边缘属性 (AxesSubplot.patches)。

更新,2022 年 4 月

较新的 Geopandas 版本 (0.10+) 有一个额外的 missing_kwds可以传递给 plot() 函数的字典,以便为给定的输入 column 参数绘制具有 NaN 值的几何图形,当绘制等值线。这会导致绘制一个新的子 PatchCollection,并且它总是(从这个版本开始,这样会改变吗?)第二个子ax._children.

为了修改这两个单独的 PatchCollection 的绘制方式,您必须执行如下操作:

fig, ax = plt.subplots(..., missing_kwds={facecolor='#000000'}, ...) 
df.plot(...) 
# NaN polygons 
c = ax._children[1] 
c.set_edgecolors(#000000) # match the facecolor in missing_kwds 
c.set_zorder(1) # this ensures it's drawn last 
 
# Drawn polygons 
c2 = ax._children[0] 
c2.set_edgecolors(retained_ec) 
c2.set_zorder(2) # this ensures it's drawn first 
 
# now call plt.savefig, plt.show etc