Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

python - AttributeError while adding colorbar in matplotlib

The following code fails to run on Python 2.5.4:

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)
ax.imshow(data, interpolation='nearest', vmin=0.5, vmax=0.99)
pl.colorbar()

pl.show()

The error message is

C:emp>python z.py
Traceback (most recent call last):
  File "z.py", line 10, in <module>
    pl.colorbar()
  File "C:Python25libsite-packagesmatplotlibpyplot.py", line 1369, in colorbar
    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
  File "C:Python25libsite-packagesmatplotlibfigure.py", line 1046, in colorbar
    cb = cbar.Colorbar(cax, mappable, **kw)
  File "C:Python25libsite-packagesmatplotlibcolorbar.py", line 622, in __init__
    mappable.autoscale_None() # Ensure mappable.norm.vmin, vmax
AttributeError: 'NoneType' object has no attribute 'autoscale_None'

How can I add colorbar to this code?

Following is the interpreter information:

Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...