Ask Your Question
2

How can I prevent Python legend from showing duplicate entries?

asked 2021-11-25 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-12-20 23:00:00 +0000

qstack gravatar image

To prevent duplicate entries in a Python legend, you can set the label attribute only for the first plot. The subsequent plots can use the '_' (underscore) character for the label attribute, which will create a hidden label that will not be displayed in the legend. Here is an example:

import matplotlib.pyplot as plt

x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [3, 6, 9]
y3 = [4, 8, 12]

plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='_')
plt.plot(x, y3, label='Line 3')

plt.legend()
plt.show()

In this example, the second plot uses '_' for the label attribute, which will not be displayed in the legend. This will prevent the duplicate 'Line 1' label from appearing in the legend.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-25 11:00:00 +0000

Seen: 7 times

Last updated: Dec 20 '21