Subtitles in the Matplotlib legend

I am making some plot with matplotlib, and I have a legend that tells the viewer from which sensors the points were recorded. There are several sensors of several types, and I would like to have subtitles in the legend to tell the viewer which sensor of each group. I have a working solution, but this is a bit hacky, shown here:

enter image description here

, : . , , . , , . , , None, . . - ? .

+4
1

, , - .

import matplotlib.pyplot as plt
import matplotlib.text as mtext


class LegendTitle(object):
    def __init__(self, text_props=None):
        self.text_props = text_props or {}
        super(LegendTitle, self).__init__()

    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        x0, y0 = handlebox.xdescent, handlebox.ydescent
        title = mtext.Text(x0, y0, r'\underline{' + orig_handle + '}', usetex=True, **self.text_props)
        handlebox.add_artist(title)
        return title


[line1] = plt.plot(range(10))
[line2] = plt.plot(range(10, 0, -1), 'o', color='red')
plt.legend(['Title 1', line1, 'Title 2', line2], ['', 'Line 1', '', 'Line 2'],
           handler_map={basestring: LegendTitle({'fontsize': 18})})

plt.show()

output

http://matplotlib.org/users/legend_guide.html.

+3

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


All Articles