'Matplotlib: Subplot heights with squared imshow
I want to plot a three-panel figure, with an imshow on the top and two other plots below. My imshow is has the same x and y dimensions, ie. is squared. The two other plots have the same x dimension, they can therefore share the x axis. However, how do I specify that all three panels have the same width?
This is my code
import matplotlib.pyplot as plt
x = np.linspace(0,100,20)
y = np.sin(x)
z = np.random.rand(100,100)
fig, (ax, ax2, ax3) = plt.subplots(nrows=3, sharex=True, figsize=(10,10), gridspec_kw={"height_ratios": [2,1,1]})
# "main" plot
ax.imshow(z)
# accessory plot #1
ax2.plot(x, y)
ax2.set_xlim(0,99)
# accessory plot #2
ax3.plot(x*2, y)
plt.show()
I don't understand the behavior here, why does my imshow not have the correct width like the two panels below?
I found a solution here, but as far as I understand this can only create one additional axis per side?
And I would like it to look like this:
Solution 1:[1]
Layout is defnitely something matplotlib could use some work on. What is happening is that you have a square figure, with height_ratios=[2, 1, 1]: the first axis (where you plot the image) has double the height of the other two. But the image you are plotting is also square, so it is using all the available height, while it has "white" space on the horizontal direction.
Try to play with figsize and maybe the height_ratios, something like this:
fig, (ax, ax2, ax3) = plt.subplots(nrows=3, sharex=True, figsize=(6,12), gridspec_kw={"height_ratios": [4,1,1]})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Davide_sd |



