I have data that results in multiple lines being plotted, I want to give these lines a single label in my legend. I think this can be better demonstrated using the example below,
a = np.array([[ 3.57, 1.76, 7.42, 6.52],
[ 1.57, 1.2 , 3.02, 6.88],
[ 2.23, 4.86, 5.12, 2.81],
[ 4.48, 1.38, 2.14, 0.86],
[ 6.68, 1.72, 8.56, 3.23]])
plt.plot(a[:,::2].T, a[:, 1::2].T, 'r', label='data_a')
plt.legend(loc='best')
As you can see at Out[23] the plot resulted in 5 distinct lines. The resulting plot looks like this
Is there any way that I can tell the plot method to avoid multiple labels? I don't want to use custom legend (where you specify the label and the line shape all at once) as much as I can.
Matplotlib gives you a nice interface to collections of lines, LineCollection. The code is straight forward
This results in the output below:
I'd make a small helper function personally, if i planned on doing it often;
An easier (and IMO clearer) way to remove duplicates (than what you have) from the
handles
andlabels
of the legend is this:A low tech solution is to make two plot calls. One that plots your data and a second one that plots nothing but carries the handle:
Here's the result:
So using will's suggestion and another question here, I am leaving my remedy here
And the new plot looks like,
Numpy solution based on will's response above.
Assuming that equal labels have equal handles, get unique labels and their respective indices, which correspond to handle indices.