Reputation: 35
I want to show multi-lines with the same label but different markers in legend.
The graph I want to plot is similar to this:
But there's no marker setting in LineCollection
, I expect each line has different marker.
Any idea? Thank you.
Upvotes: 2
Views: 902
Reputation: 339102
The picture you show stems from the legend demo. Similar to what is done there you may subclass a legend handler to create a legend of choice.
Here one may use a HandlerTuple such that one can directly supply the complete list of lines in the legend.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
class HandlerLinesVertical(HandlerTuple):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
ndivide = len(orig_handle)
a_list = []
for i, handle in enumerate(orig_handle):
y = (height / float(ndivide)) * i -ydescent
line = plt.Line2D(np.array([0,1])*width, [-y,-y])
line.update_from(handle)
line.set_marker(None)
point = plt.Line2D(np.array([.5])*width, [-y])
point.update_from(handle)
for artist in [line, point]:
artist.set_transform(trans)
a_list.extend([line,point])
return a_list
x = np.linspace(0, 5, 15)
fig, ax = plt.subplots()
markers = ["o", "s", "d", "+", "*"]
lines = []
for i, marker in zip(range(5),markers):
line, = ax.plot(x, np.sin(x) - .1 * i, marker=marker)
lines.append(line)
ax.legend([tuple(lines)], ["legend entry"], handler_map={tuple:HandlerLinesVertical()},
handleheight=8 )
plt.show()
Upvotes: 2