gpt4 book ai didi

python - 在 cartopy choropleth map 上添加值标签

转载 作者:行者123 更新时间:2023-12-01 08:29:11 26 4
gpt4 key购买 nike

我正在使用 cartopy 创建一些等值区域 map ,并希望添加一项附加功能:带有与每个国家/地区的等值区域关联的数值的标签。

Here is an example我得到的输出。

here is an example我想要什么(每个区域都有值的标签)。

我想我可以在正确的坐标上手动添加每个标签,但我确信有一种更快、更通用和更可扩展的方法来做到这一点。我花了相当多的时间进行研究,但还没有找到任何方便的解决方案,因此我们将非常感谢任何帮助。

这是我用来绘制分区统计图的函数:

def choropleth(ax, countries, geo_dict, cmap_name):
"""
Plots a choropleth map of selected countries using the values in geo_dict
as a base for the colormap

ax: matplotlib axes on which the cloropleth is drawn
countries: a list of records extracted from a shp file representing the
regions to be mapped
geo_dict: a dictionary in which the keys are ISO alpha-2 country codes and
the values the relevant data for the choropleth
cmap_name: a string with the name of the colormap to be used
"""

# value normalization for the color map
values = [geo_dict[[c.attributes['ISO_A2']][0]] for c in countries]
norm = Normalize(vmin=min(values), vmax=max(values))

cmap = plt.cm.get_cmap(cmap_name) # add ',n' to limit choropleth categories

for c in countries:
v = geo_dict[c.attributes['ISO_A2']]
sp = ShapelyFeature(c.geometry, crs,
edgecolor='k',
linewidth=0.3,
zorder = 2,
facecolor=cmap(norm(v)))
ax.add_feature(sp)

sm = plt.cm.ScalarMappable(cmap=cmap,norm=norm)
sm._A = []
plt.colorbar(sm,ax=ax)

最佳答案

:如何为每个国家添加标签?

简短回答:在 ax.add_feature() 之后,使用 ax.annotate()。您需要获取 c.geometry 的质心作为 annotate 的参数。

答案:您的代码缺少绘制标签的正确命令。在这种情况下最合适的是ax.annotate(),它应该放在ax.add_feature()之后。需要的参数包括:

  • 数据 CRS(来自您代码的 crs)
  • Axes CRS(未出现在您的代码中)

以下是应将标签添加到每个国家/地区的质心位置的代码片段:

# ... other lines of code above here
ax.add_feature(sp) # existing code

# my code follows
pnt = c.geometry.centroid
anno = c.attributes['ISO_A2'] # 'name' is also possible
# `Axes CRS` is taken from: ax.projection
# `Data CRS` is taken as `crs`
ax.annotate(anno, ax.projection.transform_point(pnt.x, pnt.y, crs))

关于python - 在 cartopy choropleth map 上添加值标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54005592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com