Gridspec spanning fractional column width

62 Views Asked by At

I'd like a plot that has two subplots in the first row, each spanning 1.5 columns, and three plots in the second row, each a column wide. Is that possible with matplotlib and gridspec? From the examples, it doesn't appear to be so. The width_ratios argument also won't work since that affects all rows.

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(10, 6))
gs = GridSpec(2, 3)

# First row (1.5 column width)
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])

# Second row (one-third width)
ax3 = plt.subplot(gs[1, 0])
ax4 = plt.subplot(gs[1, 1])
ax5 = plt.subplot(gs[1, 2])

ax1.set_title('Subplot 1')
ax2.set_title('Subplot 2')
ax3.set_title('Subplot 3')
ax4.set_title('Subplot 4')
ax5.set_title('Subplot 5')


plt.tight_layout()
plt.show()

The code above produces this. I just can't figure out how to make subplots 1 and 2 span 1.5 columns.

incorrect spacing

2

There are 2 best solutions below

0
BigBen On BEST ANSWER

Using subplot_mosaic:

axd = plt.figure(layout='constrained', figsize=(10,6)).subplot_mosaic(
    """
    AAABBB
    CCDDEE
    """
)
for i, ax in enumerate(axd.values(), start=1):
    ax.set_title(f'Subplot {i}')
plt.show()

Output: enter image description here

0
Quang Hoang On

You would want to do a 2x6 grid:

fig = plt.figure(figsize=(10, 6))
gs = GridSpec(2, 6)

# First row (1.5 column width)
ax1 = plt.subplot(gs[0, :3])
ax2 = plt.subplot(gs[0, 3:])

# Second row (one-third width)
ax3 = plt.subplot(gs[1, :2])
ax4 = plt.subplot(gs[1, 2:4])
ax5 = plt.subplot(gs[1, 4:])

ax1.set_title('Subplot 1')
ax2.set_title('Subplot 2')
ax3.set_title('Subplot 3')
ax4.set_title('Subplot 4')
ax5.set_title('Subplot 5')


plt.tight_layout()

output:

enter image description here