7

Once I have created a system of subplots in a figure with

        fig, ((ax1, ax2)) = plt.subplots(1, 2)

can I play around with the position of ax2, for example, by shifting it a little bit to the right or the left?

In other words, can I customize the position of an axes object in a figure after it has been created as a subplot element? If so, how could I code this?

Thanks for thinking along

XavierStuvw
  • 1,294
  • 2
  • 15
  • 30

1 Answers1

14

You can use commands get_position and set_position like in this example:

import matplotlib.pyplot as plt

fig, ((ax1, ax2)) = plt.subplots(1, 2)
box = ax1.get_position()
box.x0 = box.x0 + 0.05
box.x1 = box.x1 + 0.05
ax1.set_position(box)
plt.show()

which results in this:

Shifting matplotlib subplot

You'll notice I've used attributes x0 and x1 (first and last X coordinate of the box) to shift the plot in 0.05 in that axis. The logic applies to y also.

In fact should the shift be to big and the boxes will overlap (like in this image with a shift of 0.2).

big shift with overlapping plots in matplotlib

XavierStuvw
  • 1,294
  • 2
  • 15
  • 30
armatita
  • 12,825
  • 8
  • 48
  • 49