4

I am plotting a series of heatmaps using matplotlib. Without a shared y-axis, it works OK. I'm running into an issue when I try and share the y-axis though. The x-axis limits seem to get mangled.

Consider the following MWE:

import matplotlib
print matplotlib.__version__ # prints "1.4.2"

import matplotlib.pyplot as plt

data = [[1,2,3],
        [4,5,6],
        [7,8,9],
        [10,11,12]]

nrows, ncols = 1, 4
fig, axes = plt.subplots(nrows, ncols, sharey=True)

for j in range(ncols):
    xs = axes[j]

    # seems to have no impact when sharey=True
    #xs.set_xlim(-0.5, 2.5)

    xs.imshow(data, interpolation='none')   
plt.show()  

The incorrect output of this looks like:

Incorrect output with incorrect x limits

Whereas simply changing sharey=True to sharey=False results in the correct output (with the exception that I want the y-axis to be shared of course, which it now isn't):

Correct output with correct x limits

Is there a way to fix this?

Bryce Thomas
  • 10,479
  • 26
  • 77
  • 126
  • Possible duplicate of [matplotlib.pyplot.imshow: removing white space within plots when using attributes "sharex" and "sharey"](https://stackoverflow.com/questions/15077364/matplotlib-pyplot-imshow-removing-white-space-within-plots-when-using-attribute) – buzjwa Oct 03 '18 at 09:06

1 Answers1

1

Taking the answer from here:

ax.set_adjustable('box-forced')

So:

for j in range(ncols):
    xs = axes[j]
    xs.set_adjustable('box-forced')   
    xs.imshow(data, interpolation='none')

It seems that this is intentional behaviour and you need to specify this to reconcile the differences between how imshow() behaves on a single plot and how it otherwise has to on a sublplot.

Geoffrey
  • 94
  • 1
  • 7