Search code examples
pythonmatplotlibtitlesubplot

Python: title above two axes, but not above figure


I'm looking for something similar toplt.subtitle() that puts a "main title" above two subplots of my choice which are in a grid. In my plot, the title Development of model parameter and Final model parameter should be something like a main title for the two axes. Is there a function for that? Or a smooth workaround?enter image description here


Solution

  • One way would be to create an invisible axis for the common diagrams and use just the title from this axis:

    import numpy as np
    import matplotlib.pyplot as plt
    
    #function for display
    def f(t, a, b, c):
        return np.exp(a - t) * np.sin(b * t + c)
    
    fig = plt.figure()
    
    x = np.linspace(0, 10, 1000)
    #curve 1
    ax1 = fig.add_subplot(211)
    ax1.plot(x, f(x, 5, 1, 0))
    ax1.set_title("Curve 1")
    #create common axis for curve 2 and 3, remove frame and ticks, set title 
    ax23 = fig.add_subplot(223, frameon = False)
    ax23.set_xticks([])
    ax23.set_yticks([])
    ax23.set_title("Curve 2 and 3 together")
    #create curve 2
    ax2 = fig.add_subplot(245)
    ax2.plot(x, f(x, 0, 3, 0))
    #create curve 3
    ax3 = fig.add_subplot(246)
    ax3.plot(x, f(x, 2, 1, 7))
    #create curve 4
    ax4 = fig.add_subplot(224)
    ax4.plot(x, f(x, -1, 3, -3))
    ax4.set_title("Curve 4")
    #display
    plt.show()
    

    Output

    enter image description here