Getting error KeyError: 'name_long' for 'country' 'records' object "name = country.attributes['name_long']"

Getting error KeyError: 'name_long' for 'country' 'records' object "name = country.attributes['name_long']"

我从另一个页面“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)

您的 country.attributes dictionary/map 没有键 'name_long' 的值。

你的国家是Record as given by the documentation for shapereader

记录有属性,它只是一个普通的字典。您正在阅读的任何数据都没有 'name_long' 属性。

您似乎是 downloading the data from the NaturalEarthData 网站。因此,请查看那里实际可用的属性。

根据您的评论,您似乎拥有 'NAME_LONG' 密钥,但是... 'NAME_LONG' != 'name_long'