简体   繁体   English

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

[英]Make colorbar legend in Matplotlib/Cartopy

I've made a geographical heatmap using cartopy and matplotlib, of the number of users of my app, but am having trouble adding a colorbar legend: 我使用了我的应用程序用户数量的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)

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

I want to add a colorbar legend. 我想添加一个颜色条图例。 There is documentation to do so for a straightforward matplotlib plot, but I'm not sure how to do it through cartopy, where the axis is a GeoAxesSubplot . 对于简单的matplotlib图有文档可做,但我不知道如何通过cartopy进行,其中轴是GeoAxesSubplot Any help adding the legend would be appreciated. 任何帮助添加传奇将不胜感激。

I would also appreciate tips as to what library is best for these sorts of geographical heatmaps. 我也很欣赏有关哪种库最适合这些地理热图的提示。 I have to make a heatmap of users in the US next, and cartopy doesn't seem to be the best option. 接下来我必须在美国制作一个用户热图,而且纸箱似乎不是最好的选择。 Thanks! 谢谢!

I think that add_geometries() returns a FeatureArtist rather than some Matplotlib mappable object that can be passed to colorbar() . 我认为add_geometries()返回一个FeatureArtist而不是一些可以传递给colorbar() Matplotlib可映射对象。 The simplest solution I can think of is to create your own mappable and use that to create the colorbar. 我能想到的最简单的解决方案是创建自己的mappable并使用它来创建颜色条。 Try placing these lines after your country loop: 尝试在country循环后放置这些行:

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

与colorbar的等值线

Incidently, this kind of geographical heatmap is called a choropleth map . 很明显,这种地理热图称为等值区域图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM