Matplotlib:将颜色条添加到 cartopy 图像
Matplotlib: Add colorbar to cartopy image
我正在从 cartopy
中绘制国家,并按如下方式从彩色地图中添加颜色:
cmap = plt.get_cmap('viridis')
norm = matplotlib.colors.Normalize(vmin=dfSingle.min(), vmax=dfSingle.max())
dfSingle[:] = norm(dfSingle).data
kw = dict(resolution='110m', category='cultural',
name='admin_0_countries')
states_shp = shapereader.natural_earth(**kw)
shp = shapereader.Reader(states_shp)
ax = plt.axes(projection=ccrs.PlateCarree())
for record, state in zip(shp.records(), shp.geometries()):
try:
colorNormalized = dfSingle[int(record.attributes['iso_n3'])]
ax.add_geometries([state], ccrs.PlateCarree(),
facecolor=cmap(colorNormalized), edgecolor='black')
except KeyError:
ax.add_geometries([state], ccrs.PlateCarree(),
facecolor='grey', edgecolor='black')
我的数据是这样的:
In [246]: dfSingle.head()
Out[246]:
V2
12 0.179909
31 0.332297
32 0.642179
36 0.815429
48 0.215383
现在我想添加与标准化值和 cmap
对应的颜色条。但是,我不断收到错误消息:
ax.get_figure().colorbar()
AttributeError: 'GeoAxesSubplot' object has no attribute 'colorbar'
cmap.colorbar
AttributeError: 'ListedColormap' object has no attribute 'colorbar'
foo = matplotlib.cm.ScalarMappable(cmap)
ax.get_figure().colorbar(foo)
TypeError: You must first set_array for mappable
foo.set_array(dfSingle.values)
ax.get_figure().colorbar(foo)
AttributeError: 'ListedColormap' object has no attribute 'autoscale_None'
这就是我的情节现在的样子:
如何添加颜色条?
解决方法是设置_A = []
,而不是使用set_array()
函数。
sm = plt.cm.ScalarMappable(cmap=cmap)
sm._A = []
cb = plt.colorbar(sm)
cb.set_ticks([])
我正在从 cartopy
中绘制国家,并按如下方式从彩色地图中添加颜色:
cmap = plt.get_cmap('viridis')
norm = matplotlib.colors.Normalize(vmin=dfSingle.min(), vmax=dfSingle.max())
dfSingle[:] = norm(dfSingle).data
kw = dict(resolution='110m', category='cultural',
name='admin_0_countries')
states_shp = shapereader.natural_earth(**kw)
shp = shapereader.Reader(states_shp)
ax = plt.axes(projection=ccrs.PlateCarree())
for record, state in zip(shp.records(), shp.geometries()):
try:
colorNormalized = dfSingle[int(record.attributes['iso_n3'])]
ax.add_geometries([state], ccrs.PlateCarree(),
facecolor=cmap(colorNormalized), edgecolor='black')
except KeyError:
ax.add_geometries([state], ccrs.PlateCarree(),
facecolor='grey', edgecolor='black')
我的数据是这样的:
In [246]: dfSingle.head()
Out[246]:
V2
12 0.179909
31 0.332297
32 0.642179
36 0.815429
48 0.215383
现在我想添加与标准化值和 cmap
对应的颜色条。但是,我不断收到错误消息:
ax.get_figure().colorbar()
AttributeError: 'GeoAxesSubplot' object has no attribute 'colorbar'
cmap.colorbar
AttributeError: 'ListedColormap' object has no attribute 'colorbar'
foo = matplotlib.cm.ScalarMappable(cmap)
ax.get_figure().colorbar(foo)
TypeError: You must first set_array for mappable
foo.set_array(dfSingle.values)
ax.get_figure().colorbar(foo)
AttributeError: 'ListedColormap' object has no attribute 'autoscale_None'
这就是我的情节现在的样子:
如何添加颜色条?
解决方法是设置_A = []
,而不是使用set_array()
函数。
sm = plt.cm.ScalarMappable(cmap=cmap)
sm._A = []
cb = plt.colorbar(sm)
cb.set_ticks([])