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,
JavaScript
x
10
10
1
a = np.array([[ 3.57, 1.76, 7.42, 6.52],
2
[ 1.57, 1.2 , 3.02, 6.88],
3
[ 2.23, 4.86, 5.12, 2.81],
4
[ 4.48, 1.38, 2.14, 0.86],
5
[ 6.68, 1.72, 8.56, 3.23]])
6
7
plt.plot(a[:,::2].T, a[:, 1::2].T, 'r', label='data_a')
8
9
plt.legend(loc='best')
10
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.
Advertisement
Answer
I’d make a small helper function personally, if i planned on doing it often;
JavaScript
1
32
32
1
from matplotlib import pyplot
2
import numpy
3
4
5
a = numpy.array([[ 3.57, 1.76, 7.42, 6.52],
6
[ 1.57, 1.2 , 3.02, 6.88],
7
[ 2.23, 4.86, 5.12, 2.81],
8
[ 4.48, 1.38, 2.14, 0.86],
9
[ 6.68, 1.72, 8.56, 3.23]])
10
11
12
def plotCollection(ax, xs, ys, *args, **kwargs):
13
14
ax.plot(xs,ys, *args, **kwargs)
15
16
if "label" in kwargs.keys():
17
18
#remove duplicates
19
handles, labels = pyplot.gca().get_legend_handles_labels()
20
newLabels, newHandles = [], []
21
for handle, label in zip(handles, labels):
22
if label not in newLabels:
23
newLabels.append(label)
24
newHandles.append(handle)
25
26
pyplot.legend(newHandles, newLabels)
27
28
ax = pyplot.subplot(1,1,1)
29
plotCollection(ax, a[:,::2].T, a[:, 1::2].T, 'r', label='data_a')
30
plotCollection(ax, a[:,1::2].T, a[:, ::2].T, 'b', label='data_b')
31
pyplot.show()
32
An easier (and IMO clearer) way to remove duplicates (than what you have) from the handles
and labels
of the legend is this:
JavaScript
1
8
1
handles, labels = pyplot.gca().get_legend_handles_labels()
2
newLabels, newHandles = [], []
3
for handle, label in zip(handles, labels):
4
if label not in newLabels:
5
newLabels.append(label)
6
newHandles.append(handle)
7
pyplot.legend(newHandles, newLabels)
8