A few names in the legend in matplotlib

Is it possible to put multiple β€œheaders” in a legend in matplotlib? I want 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’s hard to align them correctly by manually setting positions.

+4
source share
1 answer

the closest I got to him, created an empty proxy artist. The problem in my opinion is that they are not left aligned, but the space for the (empty) marker still exists.

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()
+3
source

Source: https://habr.com/ru/post/1548669/


All Articles