13

This is related to (or rather a follow-up) to new pythonic style for shared axes square subplots in matplotlib?.

I want to have subplots sharing one axis just like in the question linked above. However, I also want no space between the plots. This is the relevant part of my code:

f, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
plt.setp(ax1, aspect=1.0, adjustable='box-forced')
plt.setp(ax2, aspect=1.0, adjustable='box-forced')

# Plot 1
ax1.matshow(pixels1, interpolation="bicubic", cmap="jet")
ax1.set_xlim((0,500))
ax1.set_ylim((0,500))

# Plot 2
ax2.matshow(pixels2, interpolation="bicubic", cmap="jet")
ax2.set_xlim((0,500))
ax2.set_ylim((0,500))

f.subplots_adjust(wspace=0)

And this is the result: enter image description here

If i comment out the two plt.setp() commands, I get some added white borders: enter image description here

How can I make the figure look like my first result, but with axes touching like in the second result?

Community
  • 1
  • 1
Michael Becker
  • 355
  • 1
  • 2
  • 10

1 Answers1

13

EDIT: The fastest way to get your result is the one described by @Benjamin Bannier, simply use

fig.subplots_adjust(wspace=0)

The alternative is to make a figure that has a width/height ratio equal to 2 (as you have two plots). This may be advisable only if you plan including the figure in a document, and you already know the columnwidth of the final document.

You can set width and height in the call to Figure(figsize=(width,height)), or as a parameter to plt.subplots(), in inches. Example:

fig, axes = plt.subplots(ncols=2, sharex=True, sharey=True,figsize=(8,4))
fig.subplots_adjust(0,0,1,1,0,0)

Screenshot:enter image description here

As @Benjamin Bannier points out, as a drawback you have zero margins. Then you can play with subplot_adjust(), but you must be careful with making space in a symmetric way if you want to keep the solution simple. An example could be fig.subplots_adjust(.1,.1,.9,.9,0,0).

gg349
  • 21,996
  • 5
  • 54
  • 64
  • 1
    Your `subplots_adjust` hides the axes which might not be what is needed. I'd suggest `subplots_adjust(hspace=0)` which exclusively removes the space between the panels. – Benjamin Bannier Mar 24 '14 at 11:42
  • Yupp, seem to have the wrong mental picture, I always mix these two up. – Benjamin Bannier Mar 24 '14 at 12:06
  • 1
    If you look in my original question, I do use `subplots_adjust(wspace=0)` and it does **not** kill the space. However, your solution using an appropriate figure size and carefully adjusting the subplot margins symmetrically **does** work and is sufficient for my purposes! I am still irritated, tough, that my original code does not work... – Michael Becker Mar 24 '14 at 13:20
  • I found my mistake! The setp() lines should happen **after** the matshow() commands (which makes sense in the pyplot world, I guess), then it works as you suggested! Thanks. – Michael Becker Mar 24 '14 at 13:25