allhands allhands - 10 months ago 66
Python Question

Matplotlib legend: labels above markers

I have a plot with multiple lines, each labelled separately. I'd like to put a legend in the plot so that individual lines can be identified. The default ordering of labels and markers looks something like:

marker : label

marker : label

marker : label

... and so on.

For various aesthetic reasons I'd like the number of columns in my legend to equal the number of lines (and labels), which I change using the

option. So, currently, my legend looks like:

marker : label      marker : label      marker : label

It would be much clearer for me, however, to have the labels above the markers in this arrangement. What I would like is something like:

label        label        label

marker    marker    marker

I'm wondering if there is a "quick fix" way to achieve such a legend.


In the end the way I went about this was to manually configure the positions of the text items in the legend using legend.get_texts() to iterate over each text object. Some dummy code:

for txt in legend.get_texts():
    txt.set_ha("center") # horizontal alignment of text item
    txt.set_x(-5) # x-position
    txt.set_y(10) # y-position

By increasing the y-position you push the label up (i.e. above the marker). Similarly by decreasing the x-position it's possible to achieve alignment over the top of the marker.