【发布时间】:2018-05-09 16:28:59
【问题描述】:
我从另一个页面“Make colorbar legend in Matplotlib/Cartopy”得到了他的示例,但是当我尝试在 Jupyter Notebook 中运行它时,它会抛出如下错误:
KeyError Traceback (most recent call last)
<ipython-input-3-55c282431f2e> in <module>()
14 ax = plt.axes(projection=ccrs.Robinson())
15 for country in shpreader.Reader(countries_shp).records():
---> 16 name = country.attributes['name_long']
17 num_users = countries[name]
18 ax.add_geometries(country.geometry, ccrs.PlateCarree(),
KeyError: 'name_long'
请帮忙!代码示例:
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)
【问题讨论】:
-
当我记录键时,它有一个键 'name_long': print(sorted(country.attributes.keys())) ['ABBREV', ... 'NAME', 'NAME_ALT', 'NAME_CIAWF'、'NAME_LEN'、'NAME_LONG'、'NAME_SORT'、'NOTE_ADM0'、'NOTE_BRK'、'POP_EST'、...'WOE_NOTE'、'featurecla'、'scalerank']
-
NAME_LONG与name_long不同 -
自然地球元数据在某些时候发生了变化,键名也被修改了。