在matplotlib的面向对象样式中,您可以获得现有图形中的当前轴,线和图像:
fig.axes
fig.axes[0].lines
fig.axes[0].images
但是我还没有找到获得现有色块的方法,我必须在第一次创建时为色条指定一个名称:
cbar = fig.colorbar(image)
如果我没有为这些名称指定名称,是否有办法获取给定图形中的colorbar对象?
答案 0 :(得分:1)
问题是颜色条被添加为"只是另一个"轴,所以它将与正常'一起列出。轴。
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
对我来说,这给出了结果:
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>]
也就是说,图中有两个轴,第二个是新的颜色条。
编辑:代码基于此处给出的答案: https://stackoverflow.com/a/2644255/2073632