views:

103

answers:

2

I am plotting a simple pair of subplots in matplotlib that are for some reason unevenly centered. I plot them as follows:

plt.figure()
# first subplot
s1 = plt.subplot(2, 1, 1)
plt.bar([1, 2, 3], [4, 5, 6])
# second subplot
s2 = plt.subplot(2, 1, 2)
plt.pcolor(rand(5,5))

# add colorbar
plt.colorbar()

# square axes
axes_square(s1)
axes_square(s2)

where axes_square is simply:

def axes_square(plot_handle):
  plot_handle.axes.set_aspect(1/plot_handle.axes.get_data_ratio()) 

The plot I get is attached. The top and bottom plots are unevenly centered. I'd like their yaxis to be aligned and their boxes to be aligned.

If I remove the plt.colorbar() call, the plots become centered. How can I have the plots centered while the colorbar of pcolor is still shown? I want the axes to be centered and have the colorbar be outside of that alignment, either to the left or to the right of the pcolor matrix.

image of plots link

Image of uncentered subplots in matplotlib

thanks.

A: 

Well, this probably isn't exactly what you want, but it'll work:

from numpy.random import rand
import matplotlib.pyplot as plt

plt.figure()
# first subplot
s1 = plt.subplot(2, 2, 2)
plt.bar([1, 2, 3], [4, 5, 6])
# second subplot
s2 = plt.subplot(2, 2, 4)
plt.pcolor(rand(5,5))

# square axes
axes_square(s1)
axes_square(s2)

s_fake = plt.subplot(2, 2, 3)
s_fake.set_axis_off()
# add colorbar
plt.colorbar()

It just makes a fake pair of cells on the left, and doesn't display anything in them. Not pretty, but it works. ;)

Also, I'm guessing that those two imports were implicit in your code ...

Craig Citro
thanks. Is there a way to do this without introducing more subplots? I am not sure why the extra subplot trick works? There should be a way to center them without... this sounds like a bug in "colorbar()" function.
A: 

Give a cax argument to colorbar to designate where you like the colorbar:

plt.colorbar(cax=plt.gcf().add_axes((0.75,0.1,0.05,0.3)))
Jouni K. Seppänen
when I do that, it erases my manual setting of x and y ticklabels on the pcolor matrix and I am also unsure how to set add_axes. How do you determine the right coordinates to pass it?Is there an easier way to get the colorbar to not interfere with the alignment of the plots if I place it horizontally rather than vertically? Thanks.
I don't see any changes to tick labels. Did you post your full code?
Jouni K. Seppänen