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.
Asked: 2021-11-25 11:00:00 +0000
Seen: 7 times
Last updated: Dec 20 '21