Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong colorbar positioning when using subplots (matplotlib)

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()
like image 715
The Dude Avatar asked Apr 17 '14 22:04

The Dude


People also ask

How do I change the position of the color bar in Matplotlib?

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.

Can the spacing be adjusted between subplots using Matplotlib?

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.


1 Answers

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)
like image 72
Molly Avatar answered Oct 05 '22 23:10

Molly