Search code examples
pythonmatplotliblegendgeopandas

Error `No handles with labels` when trying to relocate geopandas legend


My plot works fine as long as I do not attempt to change the location of its legend. (I am plotting a 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')

the resulted figure: without legend position setting

But when I use the line that now is masked as a comment, to change the legend position, it gives the following error and the legend is not shown as the figure below

No handles with labels found to put in legend.

After setting a position for legend

(I suspect if it has something to do with scheme='quantiles' cause it is not inherent of matplotlib and is added by pySAL.)

Thank you very much for your suggestions.


Solution

  • GeoDataFrame.plot provides a legend_kwds argument, which expects a dictionary. This dictionary will be passed on to either .legend or .colorbar, depending on what kind of plot you produce. So the arguments loc='upper left', bbox_to_anchor=(1, 1) will need to go into that dictionary like

    gdf.plot(..., legend=True, legend_kwds=dict(loc='upper left', bbox_to_anchor=(1, 1)))
    

    Complete runnable example:

    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()
    

    enter image description here