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:
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()
The position of the Matplotlib color bar can be changed according to our choice by using the functions from Matplotlib AxesGrid Toolkit. The placing of inset axes is similar to that of legend, the position is modified by providing location options concerning the parent box. Axes into which the colorbar will be drawn.
We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With