I want to create a legend for a plot manually which does not directly refer to any data in the plot, such as:
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
plt.plot([0, 1], [3, 2])
line = Line2D([], [], label='abc', color='red', linewidth=1.5, marker='o',
markerfacecolor='yellow', markeredgewidth=1.5, markersize=16)
plt.legend(handles=[line], numpoints=1)
plt.show()
This works great except because I cannot find a way of setting the marker edge style (i.e. solid, dashed, dotted, etc.) as well. There is no markeredgestyle property or similar for a Line2D, and setting the linestyle instead does not seem to affect the marker edge style. Is there any workaround for this?
A few approaches come to my mind but I am not sure of how feasible they are:
- Use something entirely different from Line2D. It would need to be showable in the legend, have the same formatting options as Line2D, plus the extra marker edge style. Not sure if such a class exists
- Create a custom class derived from Line2D and implement that marker edge style myself
- Create the data in the plot itself, then remove it from there while keeping it in the legend somehow. Not sure if a class which allows me to do this even in the actual chart exists. Note that it has to contain both a marker and a line. Closest thing I can think of is using scatter for the markers and plot for the lines, but that would show two legend entries (unless there is a way to combine those into a single one)
Ideally, the line style and the marker edge style could be different, but if there is a way to change the marker edge style which involves overwriting the line style I would also take it.
I am using matplotlib 1.5.3.