簡體   English   中英

在 cartopy choropleth 地圖上添加值標簽

[英]Adding value labels on a cartopy choropleth map

我正在使用 cartopy 創建一些 choropleth 地圖,並想添加一個附加功能:帶有與每個國家/地區的 choropleth 相關聯的數值的標簽。

這是我得到的輸出示例

這是我想要的示例(每個區域帶有值的標簽)。

我想我可以在正確的坐標上一個一個地手動添加每個標簽,但我相信有一種更快、更通用和更具可擴展性的方法來做到這一點。 我花了相當多的時間進行研究,但還沒有找到任何方便的解決方案,因此將非常感謝任何幫助。

這是我用來繪制等值線圖的函數:

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)       

Q : 如何為每個國家添加標簽?

簡短回答:就在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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM