Home > Software engineering >  Matplotlib gridspec: Why are these image subplots slightly different heights?
Matplotlib gridspec: Why are these image subplots slightly different heights?

Time:10-02

I want to plot several images side-by-side. These images all have the same height, but different widths. I want them all to line up neatly, so the figure looks professional. Instead, the narrower image is taking up slightly less vertical space. Here's a minimal working example of the issue:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure(figsize=(5,5))
gridspec.GridSpec(5, 5)

# plot the narrow plot
plt.subplot2grid((5, 5), (0,0), colspan=2, rowspan=5)
plt.imshow(np.random.normal(size=(5,2)))
plt.axis('off')

# plot the wide plot
plt.subplot2grid((5, 5), (0,2), colspan=3, rowspan=5)
plt.imshow(np.random.normal(size=(5,3)))
plt.axis('off')

And here's the resulting plot:

Two image subplots, the first is slightly shorter in height

Notice how the first image is ever-so-slightly smaller vertically, despite being the same pixel height, and spanning the same number of rows in the gridspec.

How do I fix this? I am open to solutions other than GridSpec.

CodePudding user response:

How about this?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig, axs = plt.subplots(1,2,figsize=(5,5), gridspec_kw={'width_ratios': [2, 3]})
axs[0].imshow(np.random.normal(size=(5,2)))
axs[1].imshow(np.random.normal(size=(5,3)))
axs[0].axis('off')
axs[1].axis('off')

Output:

enter image description here

  • Related