In search for a solution to vertically stack lines in a matplotlib legend, I came across this stack post Two line styles in legend, but I can't make the code work, I always get an error in line "legline = handler.createartists(...):
"Exception has occurred: AttributeError'NoneType' object has no attribute 'create artists'"
Here I reproduce the code(@gyger) from that stackoverflow question:
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
class HandlerTupleVertical(HandlerTuple):
def __init__(self, **kwargs):
HandlerTuple.__init__(self, **kwargs)
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
# How many lines are there.
numlines = len(orig_handle)
handler_map = legend.get_legend_handler_map()
# divide the vertical space where the lines will go
# into equal parts based on the number of lines
height_y = (height / numlines)
leglines = []
for i, handle in enumerate(orig_handle):
handler = legend.get_legend_handler(handler_map, handle)
legline = handler.create_artists(legend, handle,
xdescent,
(2*i + 1)*height_y,
width,
2*height,
fontsize, trans)
leglines.extend(legline)
return leglines
To use this code:
line1 = plt.plot(xy,xy, c='k', label='solid')
line2 = plt.plot(xy,xy+1, c='k', ls='dashed', label='dashed')
line3 = plt.plot(xy,xy-1, c='k', ls='dashed', label='dashed')
plt.legend([(line1, line2), line3], ['text', 'more text', 'even more'],
handler_map = {tuple : HandlerTupleVertical()})