Search code examples
pythonmatplotlibplotsubplot

How can I plot four subplots with different colspans?


I try to fit four images using matplotlib.pyplot like the following:

| plot1 | plot2|
|    plot3     |
|    plot4     |

Most examples I found cover three plots like these:

ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(212)

And this plots the three plots successfully (However, I don't get how it is done for ax3). Now, I want to add the plot 4 to this arrangement. Whatever I tried, I couldn't succeed.

Could you please guide me how can I achieve it?


Solution

  • In newer versions of matplotlib you can use subplot_mosaic like:

    fig, axes = plt.subplot_mosaic("AB;CC;DD")
    

    It gives you four subplots in this structure:

                      AB          | A | B |
    AB;CC;DD    ->    CC    ->    |   C   |
                      DD          |   D   |
    

    To avoid overlapping labels, enable constrained_layout:

    fig, axes = plt.subplot_mosaic("AB;CC;DD", constrained_layout=True)
    

    constrained mosaic example