1

Firstly, let me post a link to a similar post but with a slight difference.

I am having trouble to create legend with unique labels with input data of form:

    idl_t, idl_q = [[0, 12, 20], [8, 14, 24]], [[90, 60, 90], [90, 60, 90]]

and plotting is as following:

    plt.plot(idl_t, idl_q, label="Some label")

The results is that I have multiple labels of the same text. The link posted before was having similar problems the OP there was using data of format:

idl_t, idl_q = [1,2], [2,3]

which is different from my case and I am not sure if the logic there can be applied to my case

So the question is how do I avoid duplicate labels without changing data input?

loamoza
  • 128
  • 8

2 Answers2

1

It can be done in a single line, but I am afraid it does not seem to read that well.

fig, ax = plt.subplots()
for i, (x, y) in enumerate(zip(zip(*idl_t), zip(*idl_q))):
    ax.plot(x, y, label="Label" if i == 0 else "_nolabel_")

Maybe something like this is simpler to understand:

for i in range(len(idl_t)):
    ax.plot(
        [xval[i] for xval in idl_t], 
        [yval[i] for yval in idl_q],
        label="Label" if i == 0 else "_nolabel_"
    ) 

ax.legend()

In case you want to plot [0, 12, 20] with [90, 60, 90], and [8, 14, 24] with [90, 60, 90]:

for i, (x, y) in enumerate(zip(idl_t, idl_q)):
    ax.plot(x, y, label="Label" if i == 0 else "_nolabel_")

ax.legend()
plt.show()
krm
  • 847
  • 8
  • 13
1

You can get the handles and labels used to make the legend and modify them. In the code below, these labels/handles are made into a dictionary which keeps unique dictionary keys (associated with your labels here), leading to loosing duplicate labels. (You may want to manipulate them differently to achieve your goal.)

import matplotlib.pyplot as plt

idl_t, idl_q = [[0, 12, 20], [8, 14, 24]], [[90, 60, 90], [90, 60, 90]]
plt.plot(idl_t, idl_q, label="Some label")

# get legend handles and their corresponding labels
handles, labels = plt.gca().get_legend_handles_labels()

# zip labels as keys and handles as values into a dictionary, ...
# so only unique labels would be stored 
dict_of_labels = dict(zip(labels, handles))

# use unique labels (dict_of_labels.keys()) to generate your legend
plt.legend(dict_of_labels.values(), dict_of_labels.keys())

plt.show()

Plot showing unique labels in the legend.