Search code examples
pythonmatplotlibsubplot

Python: Merge subplot over two subplotcells in matplotlib or with other libaries


Based on this article of multiple subplots on matplotlib with python, it is very easy to create subplots in form of an 2x2-matrix for example. With the code from example 4 I can get the supblots of following form: enter image description here with code:

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]')
axs[0, 1].plot(x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]')
axs[1, 0].plot(x, -y, 'tab:green')
axs[1, 0].set_title('Axis [1, 0]')
axs[1, 1].plot(x, -y, 'tab:red')
axs[1, 1].set_title('Axis [1, 1]')

for ax in axs.flat:
    ax.set(xlabel='x-label', ylabel='y-label')

# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
    ax.label_outer()

My aim now are 3 supblots of following formm but I did not found a usable source in web to get this:

enter image description here


Solution

  • Simplest is probably to use subplots_mosaic: https://matplotlib.org/stable/tutorials/provisional/mosaic.html

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Some example data to display
    x = np.linspace(0, 2 * np.pi, 400)
    y = np.sin(x ** 2)
    
    fig, axd = plt.subplot_mosaic([['left', 'right'],['bottom', 'bottom']],
                                  constrained_layout=True)
    axd['left'].plot(x, y, 'C0')
    axd['right'].plot(x, y, 'C1')
    axd['bottom'].plot(x, y, 'C2')
    plt.show()
    

    Example w/ subplot_mosaic