Wrong colorbar positioning when using subplots (matplotlib)

The Dude picture The Dude · Apr 18, 2014 · Viewed 7.6k times · Source

I want to create a figure consisting of nine subplots. I really hated the fact that I needed to create ax1 to ax9 separately so I created a for loop to do so. However, when I want to include a colorbar, the colorbar is positioned right of the last subplot. This is also illustrated in the following figure:

enter image description here

What is going wrong and how can I fix this?

The image has been generated with the following code:

import numpy
import layout
import matplotlib.pylab as plt

data = numpy.random.random((10, 10))

test = ["ax1", "ax2", "ax3", "ax4", "ax5", "ax6", "ax7", "ax8", "ax9"]

fig = plt.figure(1)

for idx in range(len(test)):
    vars()[test[idx]] = fig.add_subplot(3, 3, (idx + 1))

im = ax1.imshow(data)
plt.colorbar(im)

im2 = ax3.imshow(data)
plt.colorbar(im2)

plt.show()

Answer

Molly picture Molly · Apr 18, 2014

colorbar takes an argument ax the "parent axes object(s) from which space for a new colorbar axes will be stolen." In your code you could do something like this to add a color bar next to an an axes:

im = ax1.imshow(data)
plt.colorbar(im, ax = ax1)