GeoPandas中的格式/圆形数字图例标签 [英] format/round numerical legend label in GeoPandas

查看:373
本文介绍了GeoPandas中的格式/圆形数字图例标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种格式化/四舍五入GeoPandas中的.plot()函数生成的地图中的数字图例标签的方法.例如:

I'm looking for a way to format/round the numerical legend labels in those maps produced by .plot() function in GeoPandas. For example:

gdf.plot(column='pop2010', scheme='QUANTILES', k=4)

这给了我一个带许多小数位的图例:

This gives me a legend with many decimal places:

我希望图例标签为整数.

I want the legend label to be integers.

推荐答案

由于我最近遇到了同样的问题,并且在Stack Overflow或其他站点上似乎不容易找到解决方案,我想我会发布这种方法.以防万一有用.

As I recently encountered the same issue, and a solution does not appear to be readily available on Stack Overflow or other sites, I thought I would post the approach I took in case it is useful.

首先,是使用geopandas世界地图的基本情节:

First, a basic plot using the geopandas world map:

# load world data set    
world_orig = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world = world_orig[(world_orig['pop_est'] > 0) & (world_orig['name'] != "Antarctica")].copy()
world['gdp_per_cap'] = world['gdp_md_est'] / world['pop_est']

# basic plot
fig = world.plot(column='pop_est', figsize=(12,8), scheme='fisher_jenks', 
                 cmap='YlGnBu', legend=True)
leg = fig.get_legend()
leg._loc = 3
plt.show()

我使用的方法依赖于matplotlib.legend.Legend对象的get_texts()方法,然后遍历leg.get_texts()中的项目,将文本元素分为上下限,然后使用格式创建一个新字符串并使用set_text()方法进行设置.

The method I used relied on the get_texts() method for the matplotlib.legend.Legend object, then iterating over the items in leg.get_texts(), splitting the text element into the lower and upper bounds, and then creating a new string with formatting applied and setting this with the set_text() method.

# formatted legend
fig = world.plot(column='pop_est', figsize=(12,8), scheme='fisher_jenks', 
                 cmap='YlGnBu', legend=True)
leg = fig.get_legend()
leg._loc = 3

for lbl in leg.get_texts():
    label_text = lbl.get_text()
    lower = label_text.split()[0]
    upper = label_text.split()[2]
    new_text = f'{float(lower):,.0f} - {float(upper):,.0f}'
    lbl.set_text(new_text)

plt.show()

这很大程度上是一种尝试和错误"的方法,因此,如果有更好的方法,我也不会感到惊讶.不过,也许这会有所帮助.

This is very much a 'trial and error' approach, so I wouldn't be surprised if there were a better way. Still, perhaps this will be helpful.

这篇关于GeoPandas中的格式/圆形数字图例标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆