Ricky Robinson
Ricky Robinson

Reputation: 22893

Matplotlib: reorder subplots

Say that I have a figure fig which contains two subplots as in the example from the documentation: enter image description here

I can obtain the two axes (the left one being ax1 and the right one ax2) by just doing:

ax1, ax2 = fig.axes

Now, is it possible to rearrange the subplots? In this example, to swap them?

Upvotes: 6

Views: 6011

Answers (1)

Joe Kington
Joe Kington

Reputation: 284562

Sure, as long as you're not going to use subplots_adjust (and therefore tight_layout) after you reposition them (you can use it safely before).

Basically, just do something like:

import matplotlib.pyplot as plt

# Create something similar to your pickled figure......
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot(range(10), 'r^-')
ax1.set(title='Originally on the left')

ax2.plot(range(10), 'gs-')
ax2.set(title='Originally on the right')

# Now we'll swap their positions after they've been created.
pos1 = ax1.get_position()
ax1.set_position(ax2.get_position())
ax2.set_position(pos1)

plt.show()

enter image description here

Upvotes: 8

Related Questions