Make color legend in Matplotlib / Cartopy

I made a geographical memory card using cartographic and matplotlib, the number of users of my application, but I had problems adding a color bar legend:

import cartopy.crs as ccrs import cartopy.io.shapereader as shpreader import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np cmap = mpl.cm.Blues # Countries is a dictionary of {"country_name": number of users}, for example countries = {"United States": 100, "Canada": 50, "China": 10} max_users = float(max(countries.values())) shapename = 'admin_0_countries' countries_shp = shpreader.natural_earth(resolution='110m', category='cultural', name=shapename) ax = plt.axes(projection=ccrs.Robinson()) for country in shpreader.Reader(countries_shp).records(): name = country.attributes['name_long'] num_users = countries[name] ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=cmap(num_users/max_users, 1)) plt.savefig('iOS_heatmap.png', transparent=True, dpi=900) 

which produces enter image description here

I want to add a color bar legend. There is documentation to do this for a simple matplotlib plot, but I'm not sure how to do this using cartography, where the axis is GeoAxesSubplot . Any help adding a legend would be appreciated.

I also appreciate tips on which library is best suited for these types of maps. Next time I have to make a heat map of users in the USA, and cartography does not seem to be the best option. Thanks!

+6
source share
1 answer

I think add_geometries() returns FeatureArtist instead of some Matplotlib display object, which can be passed to colorbar() . The simplest solution that I can think of is to create my own display method and use it to create a colorbar. Try placing these lines after the country loop:

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

choropleth with colorbar

Apparently, such a geographical heatmap is called the choropleth map .

+4
source

Source: https://habr.com/ru/post/1013439/


All Articles