Matplotlib. Align subplot with Bbox

Viewed 685

I have a grid of 6 subplots. The last subplot is square. I need to move it to the left so that its left y-axis is perfectly aligned with the y-axis of the plot above it. I know I can get and set the Bbox parameters, but I can't move it in the right direction. Whether I increase or decrease x1 and x2, it always seems to move to the right.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 3)
fig.tight_layout(pad=3.0)
fig.set_figwidth(30)
fig.set_figheight(15)

axs[1, 2].set_aspect('equal')

print(axs[1, 2].get_position())

The print command returns:

Bbox(x0=0.7620938740079364, y0=0.16765873015873023, x1=0.8925502232142856, y1=0.4285714285714286)

enter image description here

2 Answers

The .get_position() method indeed returns the bounding box of given axes. The idea is to use the Bbox of the axes right above the square axes in order to align them with it. This can be done with:

import matplotlib.pyplot as plt

# the figure size can be set directly from here
# I used smaller figure size than in your example for visibility
fig, axs = plt.subplots(2, 3, figsize=(15, 7))
fig.tight_layout(pad=3.0)

axs[1, 2].set_aspect('equal')

# extract positions of square and above axes
p02 = axs[0, 2].get_position()
p12 = axs[1, 2].get_position()

# make square axes with left position taken from above axes, and set position
p12 = [p02.x0, p12.y0, p12.width, p12.height]
axs[1, 2].set_position(p12)

plt.show()

Which results in:

left-align axes matplotlib subplot

Related