plot - 自定义图例标签 - geopandas.plot()
问题描述
我和一位同事一直在尝试设置自定义图例标签,但到目前为止都失败了。下面的代码和详细信息 - 非常感谢任何想法!
笔记本:在这里上传的玩具示例
目标:将图例中使用的默认比率值更改为相应的百分比值
问题:无法弄清楚如何访问图例对象或传递legend_kwds
给geopandas.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 安装...
解决方案
我自己也遇到过这个问题。按照您指向 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])
推荐阅读
- django - 如何在 Heroku 上使用 django 自动创建超级用户?
- google-apps-script - 谷歌表格:如何制作一个宏/脚本,对于所有选定的行,在下面插入两行,然后复制并粘贴原始内容?
- python - 如何从列表中删除项目及其在其他列表中的关联项目
- android - 在 Android 上,是否有用于存储共享首选项的线程安全方法?
- python - 列表有问题并找到 Python
- python - 如何操作 3D 数组以将笛卡尔坐标转换为球坐标
- python - 将 tweepy 流数据转换为数据帧
- authentication - 如何在 axios 插件中使用 Nuxt $auth (How to add Token to all axios requests)
- python - Python - 折叠具有相同名称的列
- angular - 在我的 ionic 仪表板页面中使用超级选项卡,当我进入仪表板页面时,我的选项卡页面都在加载。我希望它们仅在请求时加载