2

I'm drawing countries from cartopy, and adding colors from a color map as follows:

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')

and my data looks like this:

In [246]: dfSingle.head()
Out[246]: 
V2
12    0.179909
31    0.332297
32    0.642179
36    0.815429
48    0.215383

Now I would like to add the colorbar corresponding to the normalized values and the cmap. However, I keep getting errors:

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'

This is how my plot looks right now:

image without colorbar

How can I add the colorbar?

FooBar
  • 15,724
  • 19
  • 82
  • 171
  • Isn't this just a matplotlib question? http://stackoverflow.com/a/11558629/741316 – pelson Mar 09 '16 at 08:21
  • @pelson The first part is a `cartopy` problem: `ax.get_figure().colorbar()` does not work when the axes is a `GeoAxesSubplot` created with cartopy. Neither does `ax.colorbar()`. It would be great if it worked and [the colorbar axis got the right height](http://stackoverflow.com/questions/30030328/correct-placement-of-colorbar-relative-to-geo-axes-cartopy). However, as long as this is not changed, `plt.colorbar(sm, cax=ax)` should work. – j08lue Apr 04 '16 at 08:32

1 Answers1

3

The solution is to set _A = [], instead of using the set_array() function.

sm = plt.cm.ScalarMappable(cmap=cmap)
sm._A = []
cb = plt.colorbar(sm)
cb.set_ticks([])
FooBar
  • 15,724
  • 19
  • 82
  • 171