Search code examples
pythonmatplotlibplotlabellegend

Multiple titles in legend in matplotlib


Is it possible to put multiple "titles" in a legend in matplotlib? What I want is something like:

Title 1
x label 1
o label2

Title 2
^ label 3
v label 4

...

in case I have 4 curves or more. Because if I use more than 1 legend, it is difficult to get them aligned properly setting the positions manually.


Solution

  • the closest i got to it, was creating an empty proxy artist. Problem in my opinion is that they are not left aligned but the space for the (empty) marker is still there.

    from matplotlib.patches import Rectangle
    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 1, 100)
    
    # the comma is to get just the first element of the list returned
    plot1, = plt.plot(x, x**2) 
    plot2, = plt.plot(x, x**3)
    
    title_proxy = Rectangle((0,0), 0, 0, color='w')
    
    plt.legend([title_proxy, plot1, title_proxy, plot2], 
               ["$\textbf{title1}$", "label1","$\textbf{title2}$", "label2"])
    plt.show()