Moving marker position inside legend

Question:

I have a plot in which I need information encoded in line-style, color and markers.
However, when I create a legend, the markers cover a significant part of the lines, resulting in poorly recognizable line-styles. Example:

markers obscuring line-style in the legend

Is it possible to move the markers to the side (left or right), so that the whole line and its line-style is visible? Something like the following (manually moved in inkscape):

markers moved to side not to obscure line-style in the legend

Asked By: serycjon

||

Answers:

An idea could be to draw a longer handle (e.g. plt.legend(handlelength=4.0)). Also, instead of one point in the center, two points could be used, one at each end (plt.legend(numpoints=2)).

This is how an example could look like:

import matplotlib.pyplot as plt

plt.plot([0, 1], [2, 1], ls='-.', marker='D', color='r', label='A')
plt.plot([0, 1], [1, 0], ls='--', marker='D', color='b', label='B')
plt.legend(numpoints=2, handlelength=4.0)
plt.show()

legend with longer handles

A more involved approach would be to use the new tuple handler (legend guide) and create tuples with two handlers. The first handler would only contain the linestyle (removing the marker) and the second handler would only contain the marker (removing the linestyle):

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
from copy import copy

plt.plot([0, 1], [2, 1], ls='-.', marker='D', color='r', label='A')
plt.plot([0, 1], [1, 0], ls='--', marker='D', color='b', label='B')
handles, labels = plt.gca().get_legend_handles_labels()
new_handles = []
for h in handles:
    h1 = copy(h)
    h1.set_marker('')
    h2 = copy(h)
    h2.set_linestyle('')
    new_handles.append((h1, h2))
plt.legend(handles=new_handles, labels=labels, handlelength=4.0,
           handler_map={tuple: HandlerTuple(ndivide=None)})
plt.show()

legend with tuple handler

Answered By: JohanC
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.