6

In matplotlib's object oriented style you can get the current axes, lines and images in an existing figure:

fig.axes
fig.axes[0].lines
fig.axes[0].images

But I haven't found a way to get the existing colorbars, I have to assign the colorbar a name when first creating it:

cbar = fig.colorbar(image)

Is there any way to get the colorbar objects in a given figure if I didn't assign them names?

firescape
  • 307
  • 2
  • 13

1 Answers1

4

The problem is that the colorbar is added as "just another" axis, so it will be listed with the 'normal' axes.

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

For me, this gives the result:

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

That is, there are two axes in your figure, the second one is the new colorbar.

Edit: Code is based on answer given here: https://stackoverflow.com/a/2644255/2073632

Community
  • 1
  • 1
RoG
  • 828
  • 9
  • 14