在 cartopy choropleth 地图上添加价值标签

Adding value labels on a cartopy choropleth map

我正在使用 cartopy 创建一些等值统计图,并想添加一个附加功能:带有与每个 country/region.

等值统计相关联的数值的标签

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))