尝试重新定位 geopandas 图例时出现“无标签句柄”错误

Bob*_*byF 2 python matplotlib legend geopandas

只要我不尝试更改其图例的位置,我的情节就可以正常工作。(我正在绘制一个 GeoDataFrame。)

# %%
ax = NE_shp.plot(column=NE_shp.iloc[:,4], figsize=(10,3), scheme='quantiles', edgecolor='k', k=10, legend=True)

#ax.legend(loc='upper left', bbox_to_anchor=(1, 1)) #This is the line for relocating legend

ax.set_title('The Map', fontsize=16)
ax.axis('off')
Run Code Online (Sandbox Code Playgroud)

结果图: 没有图例位置设置

但是当我使用现在被屏蔽的行作为注释来更改图例位置时,会出现以下错误并且图例未显示如下图

No handles with labels found to put in legend.

为图例设置位置后

(我怀疑它是否与scheme='quantiles'原因有关,它不是 matplotlib 固有的,而是由 pySAL 添加的。)

非常感谢您的建议。

Imp*_*est 6

GeoDataFrame.plot提供一个legend_kwds参数,它需要一个字典。这本词典将传递给.legend.colorbar,具体取决于您生成的图类型。所以参数loc='upper left', bbox_to_anchor=(1, 1)需要进入那个字典,就像

gdf.plot(..., legend=True, legend_kwds=dict(loc='upper left', bbox_to_anchor=(1, 1)))
Run Code Online (Sandbox Code Playgroud)

完整的可运行示例:

import geopandas as gpd
print(gpd.__version__)   ## 0.5
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt 

gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) 
gdf['quant']=np.random.rand(len(gdf))*100-20

fig, ax = plt.subplots(figsize=(9,4))
fig.subplots_adjust(right=0.7)
gdf.plot(column='quant', scheme='quantiles', edgecolor='k', k=10, 
         legend=True, legend_kwds=dict(loc='upper left', bbox_to_anchor=(1, 1)), ax=ax)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明