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

标签 python matplotlib choropleth map-projections cartopy

我正在使用 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/

相关文章:

python - Discord bot 帮助命令的类别

python - Matplotlib - 绘制非均匀线分布

javascript - Leaflet - 随着时间的推移交互式等值线图

r - 使用 ggplot2 和 ggmap 在 R 中制作邮政编码 choropleth

python - Matplotlib 等值线图绘制两个不同的数据

python - 列表项在排序/复制后保持相同的内存地址

python - cx_Freeze 以包含依赖的 py 文件

python - Linux 上的 xlwings 替代方案

python - Matplotlib:颜色图可以暗示不同的默认规范化吗?

python - 绘制数据帧时出现内存错误(matplotlib)