AttributeError while adding colorbar in matplotlib

(This is a very old question I know) The reason you are seeing this issue is because you have mixed the use of the state machine (matplotlib.pyplot) with the OO approach of adding images to an axes.

The plt.imshow function differs from the ax.imshow method in just one subtly different way. The method ax.imshow:

  • creates and returns an Image which has been added to the axes

The function plt.imshow:

  • creates and returns an Image which has been added to the current axes, and sets the image to be the "current" image/mappable (which can then be automatically picked up by the plt.colorbar function).

If you want to be able to use the plt.colorbar (which in all but the most extreme cases, you do) with the ax.imshow method, you will need to pass the returned image (which is an instance of a ScalarMappable) to plt.colorbar as the first argument:

plt.imshow(image_file)
plt.colorbar()

is equivalent (without using the state machine) to:

img = ax.imshow(image_file)
plt.colorbar(img, ax=ax)

If ax is the current axes in pyplot, then the kwarg ax=ax is not needed.


Note: I am using python 2.6.2. The same error was raised with your code and the following modification solved the problem.

I read the following colorbar example: http://matplotlib.sourceforge.net/examples/pylab_examples/colorbar_tick_labelling_demo.html

from matplotlib import pylab as pl
import numpy as np

data = np.random.rand(6,6)
fig = pl.figure(1)
fig.clf()
ax = fig.add_subplot(1,1,1)
img = ax.imshow(data, interpolation='nearest', vmin=0.5, vmax=0.99)
fig.colorbar(img)

pl.show()

Not sure why your example didn't work. I'm not that familiar with matplotlib.


I found another solution to this problem in a tutorial.

The code below, will work well for the plt.imshow() method:

def colorbar(Mappable, Orientation='vertical', Extend='both'):
    Ax = Mappable.axes
    fig = Ax.figure
    divider = make_axes_locatable(Ax)
    Cax = divider.append_axes("right", size="5%", pad=0.05)
    return fig.colorbar(
        mappable=Mappable, 
        cax=Cax,
        use_gridspec=True, 
        extend=Extend,  # mostra um colorbar full resolution de z
        orientation=Orientation
    )

fig, ax = plt.subplots(ncols=2)

img1 = ax[0].imshow(data)
colorbar(img1)

img2 = ax[1].imshow(-data)
colorbar(img2)

fig.tight_layout(h_pad=1)
plt.show()

It may not work well with other plotting methods. For example, it did not work with Geopandas Geodataframe plot.