【问题标题】:Error `No handles with labels` when trying to relocate geopandas legend尝试重新定位 geopandas 图例时出现错误“没有带有标签的句柄”
【发布时间】:2020-05-06 21:47:31
【问题描述】:

只要我不尝试更改图例的位置,我的情节就可以正常工作。 (我正在绘制一个 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')

结果图:

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

No handles with labels found to put in legend.

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

非常感谢您的建议。

【问题讨论】:

  • Get them before trying to move It - handles, labels = x.get_legend_handles_labels(); ax.legend(handles, labels)
  • @wwii 如果可行,也可以致电ax.legend,对吗?或者反过来说,因为ax.get_legend_handles_labels 返回一个空列表,ax.legend() 不会产生图例。
  • @ImportanceOfBeingErnest ......嗯,我想这是有道理的。使用玩具 DataFrame,OP 的代码可以工作。
  • @wwii 即使使用玩具数据框,它也无法开箱即用。见下文。
  • @ImportanceOfBeingErnest .. 抱歉正在使用 Pandas DataFrame 来查看可能发生的情况。

标签: python matplotlib legend geopandas


【解决方案1】:

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

完整的可运行示例:

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

【讨论】:

  • 非常感谢。它工作得很好。只是一个跟进。在哪里可以找到可用于控制图例的所有相关参数? (例如,图例中每个标签的右侧部分是不需要的。我正在寻找一种去除右侧的方法)。 ?再次
  • 哦。我想我找到了他们here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 2019-05-23
  • 2021-10-24
相关资源
最近更新 更多