自定义图例标签 - geopandas.plot()

时间:2018-05-20 14:15:18

标签: plot geopandas legend-properties

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

笔记本:toy example uploaded here

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

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

数据:KCMO metro area counties

摘自玩具示例

第1步:读取数据

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

选项1 - 将ax的图例设为suggested here

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_来自{{ 3}} - Geopandas's plotting.py - 似乎没有通过......

# 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时遇到了GeoDataFrame.plot() is simply a wrapper - 其他this conversation明确指出legend_kwds并非最近发布的GeoPandas(v0.3.0)。据推测,这意味着我们需要从GitHub master源代码编译而不是使用pip / conda进行编译...

1 个答案:

答案 0 :(得分:2)

我本人只是遇到了这个问题。在链接到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])