首页 > 解决方案 > 自定义图例标签 - geopandas.plot()

问题描述

我和一位同事一直在尝试设置自定义图例标签,但到目前为止都失败了。下面的代码和详细信息 - 非常感谢任何想法!

笔记本:在这里上传的玩具示例

目标:将图例中使用的默认比率值更改为相应的百分比值

问题:无法弄清楚如何访问图例对象或传递legend_kwdsgeopandas.GeoDataFrame.plot()

数据:KCMO都会区县

玩具示例的节选

第一步:读取数据

# imports
import geopandas as gpd
import matplotlib.pyplot as plt
%matplotlib inline
# read data
gdf = gpd.read_file('kcmo_counties.geojson')

ax选项 1 -按照此处的建议获取图例:

ax = gdf.plot('val', legend=True)
leg = ax.get_legend()
print('legend object type: ' + str(type(leg))) # <class NoneType>
plt.show()

选项 2:传递legend_kwds字典 - 我假设我在这里做错了(并且显然没有完全理解底层细节),但是_doc_来自Geopandas 的 plotting.py - 其中GeoDataFrame.plot() 只是一个包装器- 没有似乎通过了……

# create number of tick marks in legend and set location to display them
import numpy as np
numpoints = 5
leg_ticks = np.linspace(-1,1,numpoints)

# create labels based on number of tickmarks
leg_min = gdf['val'].min()
leg_max = gdf['val'].max()
leg_tick_labels = [str(round(x*100,1))+'%' for x in np.linspace(leg_min,leg_max,numpoints)]
leg_kwds_dict = {'numpoints': numpoints, 'labels': leg_tick_labels}

# error "Unknown property legend_kwds" when attempting it:
f, ax = plt.subplots(1, figsize=(6,6))
gdf.plot('val', legend=True, ax=ax, legend_kwds=leg_kwds_dict)

更新 刚刚遇到这个关于添加的对话legend_kwds- 还有这个其他错误?这清楚地表明legend_kwds在最近发布的 GeoPandas (v0.3.0) 中没有。据推测,这意味着我们需要从 GitHubmaster源代码编译,而不是使用 pip/conda 安装...

标签: plotgeopandaslegend-properties

解决方案


我自己也遇到过这个问题。按照您指向 Geopandas 源代码的链接后,颜色条似乎已作为第二个轴添加到图中。所以你必须做这样的事情来访问颜色条标签(假设你已经用 绘制了一个叶绿素legend=True):

# Get colourbar from second axis
colourbar = ax.get_figure().get_axes()[1]

完成此操作后,您可以像这样操作标签:

# Get numerical values of yticks, assuming a linear range between vmin and vmax:
yticks = np.interp(colourbar.get_yticks(), [0,1], [vmin, vmax])

# Apply some function f to each tick, where f can be your percentage conversion
colourbar.set_yticklabels(['{0:.2f}%'.format(ytick*100) for ytick in yticks])

推荐阅读