由于我最近遇到了同样的问题,并且 Stack Overflow 或其他网站上似乎没有现成的解决方案,因此我想我会发布我采取的方法,以防万一它有用。
首先,使用的基本图geopandas
世界地图:
# 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()
我使用的方法依赖于get_texts()
方法为matplotlib.legend.Legend
对象,然后迭代中的项目leg.get_texts()
,将文本元素拆分为下限和上限,然后创建一个应用格式的新字符串,并使用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()
这在很大程度上是一种“反复试验”的方法,所以如果有更好的方法,我不会感到惊讶。不过,也许这会有帮助。