Reputation: 3323
I am creating some choropleth maps using cartopy and would like to add an additional feature: labels with the number values associated to the choropleth for each country/region.
Here is an example of the output I am getting.
And here is an example of what I would like to have (labels with values on each region).
I guess I could manually add each label one by one on the right coordinates, but I'm sure that there a faster, more generic and more scalable way to do it. I've spent quite some time researching but haven't found any convenient solution, so any help would be strongly appreciated.
This is the function that I am using to plot the choropleth map:
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)
Upvotes: 1
Views: 1605
Reputation: 18812
Q: How to add label for each country?
Short Answer: Just after ax.add_feature()
, use ax.annotate()
. You will need to get the centroid of c.geometry as a parameter of annotate.
Answer: Your code is missing the proper command to plot the labels. The most appropriate in this case is ax.annotate()
, which should be placed after ax.add_feature()
. The parameters needed include:
crs
from your code)Here is the snippet code that should add the labels to the centroid positions of each country:
# ... 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))
Upvotes: 3