Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
Ricky Robinson Avatar asked Mar 17 '14 15:03

Ricky Robinson


1 Answers

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

like image 141
Joe Kington Avatar answered Nov 13 '22 12:11

Joe Kington