在matplotlib中添加colorbar时出现AttributeError

50 投票
4 回答
88510 浏览
提问于 2025-04-15 21:38

以下代码在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()

错误信息是

C:\temp>python z.py
Traceback (most recent call last):
  File "z.py", line 10, in <module>
    pl.colorbar()
  File "C:\Python25\lib\site-packages\matplotlib\pyplot.py", line 1369, in colorbar
    ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
  File "C:\Python25\lib\site-packages\matplotlib\figure.py", line 1046, in colorbar
    cb = cbar.Colorbar(cax, mappable, **kw)
  File "C:\Python25\lib\site-packages\matplotlib\colorbar.py", line 622, in __init__
    mappable.autoscale_None() # Ensure mappable.norm.vmin, vmax
AttributeError: 'NoneType' object has no attribute 'autoscale_None'

我该如何在这段代码中添加颜色条呢?

以下是解释器的信息:

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

4 个回答

1

我在一个教程中找到了这个问题的另一个解决办法。

下面的代码可以很好地用于plt.imshow()这个方法:

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

不过,这个方法可能在其他绘图方法上效果不好。比如,它在Geopandas的Geodataframe绘图时就不太管用。

89

(我知道这是个很老的问题)你遇到这个问题的原因是因为你把状态机(matplotlib.pyplot)和面向对象的方法混在一起使用了,尤其是在给坐标轴添加图片时。

plt.imshow这个函数和ax.imshow这个方法有一个微妙的不同。

  • ax.imshow方法会创建并返回一个已经添加到坐标轴上的图像。

plt.imshow函数则会:

  • 创建并返回一个已经添加到当前坐标轴上的图像,并将这个图像设置为“当前”的图像/可映射对象(这样plt.colorbar函数就能自动使用这个图像)。

如果你想使用plt.colorbar(在大多数情况下你都会需要),而且是用ax.imshow方法的话,你需要把返回的图像(这是一个ScalarMappable的实例)作为第一个参数传给plt.colorbar

plt.imshow(image_file)
plt.colorbar()

这和不使用状态机的情况是等价的:

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

如果ax是当前的坐标轴,那么kwarg ax=ax就不需要了。

32

注意:我使用的是python 2.6.2。你的代码也出现了同样的错误,下面的修改解决了这个问题。

我看了这个颜色条的例子: 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()

不太清楚为什么你的例子没有成功。我对matplotlib不太熟悉。

撰写回答