matplotlib:有什么方法可以获取现有的颜色条?

fir*_*ape 5 python matplotlib

在 matplotlib 的面向对象风格中,您可以获取现有图形中的当前轴、线和图像:

fig.axes
fig.axes[0].lines
fig.axes[0].images
Run Code Online (Sandbox Code Playgroud)

但是我还没有找到获取现有颜色条的方法,我必须在第一次创建颜色条时为其分配一个名称:

cbar = fig.colorbar(image)
Run Code Online (Sandbox Code Playgroud)

如果我没有为它们指定名称,有没有办法在给定的图形中获取颜色条对象?

RoG*_*RoG 4

问题在于颜色条被添加为“只是另一个”轴,因此它将与“正常”轴一起列出。

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(6,6)
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(1,1,1)
cax = ax.imshow(data, interpolation='nearest', vmin=0.5, vmax=0.99)
print "Before adding the colorbar:"
print fig.axes
fig.colorbar(cax)
print "After adding the colorbar:"
print fig.axes
Run Code Online (Sandbox Code Playgroud)

对我来说,这给出了结果:

Before adding the colorbar:
[<matplotlib.axes._subplots.AxesSubplot object at 0x00000000080D1D68>]
After adding the colorbar:
[<matplotlib.axes._subplots.AxesSubplot object at 0x00000000080D1D68>,
<matplotl ib.axes._subplots.AxesSubplot object at 0x0000000008268390>]
Run Code Online (Sandbox Code Playgroud)

也就是说,你的图中有两个轴,第二个是新的颜色条。

编辑:代码基于此处给出的答案: https ://stackoverflow.com/a/2644255/2073632