Home > Back-end >  How to get aligments of subplots and subfigures right with constrained_layout in matplotlib?
How to get aligments of subplots and subfigures right with constrained_layout in matplotlib?

Time:12-15

I have the following sub figures and sub plots in matplotlib"

Sub figure 1 > ax1
Sub figure 2 > Sub plot 1  > ax2
             > Sub plot 2  > ax3

The MWE is given below. The problem with the present MWE is that for numbers of different magnitudes on y-axes; the alignment between ax1, ax2, and ax3 are broken as shown in the green box of the figure.

enter image description here

Setting the contstrained_layout to False I can get the alignments right, but messes the spacings. So I need the constrained_layout set to True, but need to get the alignments of ax1, ax2, ax3 right. Are there any methods that I am missing to fix this alignment?

MWE

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 100, 100)
y = x ** 2
y2 = x ** 10

figure = plt.figure(figsize=(10, 8), constrained_layout=True)
figure.clf()
subfigs = figure.subfigures(2, 1, height_ratios=[1, 1], hspace=0.05, wspace=0.05)

plots = subfigs[0].subplots()
ax1 = plt.gca()
ax1.plot(x, y2)

sub_plot = subfigs[1].subplots(2,1)
ax2 = sub_plot[0]
ax2.plot(x, y)

ax3 = sub_plot[1]
ax3.plot(x, y)

plt.show()

CodePudding user response:

The point of a subfigure is to make the subfigures independent. If you want axes spines to line up, then you need to keep the axes in the same figure:


import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 100, 100)
y = x ** 2
y2 = x ** 10

figure = plt.figure(figsize=(5, 4), constrained_layout=True)

ax1, ax2, ax3 = figure.subplots(3, 1, gridspec_kw={'height_ratios': [2, 1, 1]})

ax1.plot(x, y2)
ax2.plot(x, y)
ax3.plot(x, y)

plt.show()

Note that you can set the height_ratios and the width_ratios using the gridspec_kw argument.

enter image description here

For more explanation, you can see: https://matplotlib.org/stable/tutorials/intermediate/arranging_axes.html

  • Related