从 GeoPandas 图中重新定位图例

Relocating legend from GeoPandas plot

我正在使用 GeoPandas 绘图功能绘制带有图例的地图。当我绘图时,我的图例出现在图的右上角。这是它的样子:

我想将图例移到图表的下部。对于普通的 matplotlib 图,我通常会做这样的事情:

fig, ax = plt.subplots(1, figsize=(4.5,10))
lima_bank_num.plot(ax=ax, column='quant_cuts', cmap='Blues', alpha=1, legend=True)
ax.legend(loc='lower left')

但是,这个修改没有被考虑进去。

您可以使用 ax.get_legend() 访问 ax 实例上定义的图例。然后,您可以使用 set_bbox_to_anchor 方法更新图例的位置。从头开始创建图例时,这并不提供与 loc 关键字相同的易用性,但确实可以控制放置。因此,对于您的示例,类似于:

leg = ax.get_legend()
leg.set_bbox_to_anchor((0., 0., 0.2, 0.2))

一点点 documentation of set_bbox_to_anchor,虽然我觉得它不是特别有用。

这可以使用 legend_kwds 参数来完成:

df.plot(column='values', legend=True, legend_kwds={'loc': 'lower right'});

如果您有一个水平图例,并且您只是想缩小图例和情节之间的差距,我建议使用 https://gis.stackexchange.com/a/330175/32531 中详述的 colorbar 方法,同时传递 pad legend_kwd 参数:

legend_kwds={"orientation": "horizontal", "pad": 0.01}