在Matplotlib/Cartopy中创建颜色条图例

goo*_*cow 6 python matplotlib heatmap colorbar cartopy

我使用了我的应用程序用户数量的cartopy和matplotlib制作了地理热图,但是在添加颜色条图例时遇到了问题:

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)
Run Code Online (Sandbox Code Playgroud)

哪个产生 在此输入图像描述

我想添加一个颜色条图例.有一个文件要做一个简单的matplotlib图,但我不知道如何通过cartopy,轴是a GeoAxesSubplot.任何帮助添加传奇将不胜感激.

我也很欣赏有关哪种库最适合这些地理热图的提示.接下来我必须在美国制作一个用户热图,而且纸箱似乎不是最好的选择.谢谢!

Ded*_*tos 6

我认为这会add_geometries()返回一个FeatureArtist可以传递给的Matplotlib可映射对象colorbar()。我能想到的最简单的解决方案是创建自己的mappable并使用它来创建颜色条。尝试在country循环之后放置以下行:

sm = plt.cm.ScalarMappable(cmap=cmap,norm=plt.Normalize(0,1))
sm._A = []
plt.colorbar(sm,ax=ax)
Run Code Online (Sandbox Code Playgroud)

带彩条的管弦

顺便说一句,这种地理热图被称为Choropleth地图