plt.legend() only shows the first letter of the legend string

Viewed 139

In the following code the legend should be the names specified in the list, but as you can see in the figure, only the first letter is shown.

bench = ['AA', 'BB']
offset = 0
for b in bench:
    L1 = [12+offset, 5+offset, 3+offset]
    L2 = [20+offset, 22+offset, 25+offset]
    offset += 5
    
    plt.plot(L1, L2)
    plt.legend(b)
    plt.savefig('test4.png')
    plt.show()

enter image description here

enter image description here

How can I fix that?

2 Answers

You have used legend not properly and you need to use the label argument.

import matplotlib.pyplot as plt

bench = ['AA', 'BB']
offset = 0
for b in bench:
    L1 = [12+offset, 5+offset, 3+offset]
    L2 = [20+offset, 22+offset, 25+offset]
    offset += 5
    
    plt.plot(L1, L2, label=b)
    plt.legend()
    plt.savefig('test4.png')
    plt.show()

enter image description here

plt.legend() takes an iterable of labels, so if you only need the label with everything else unchanged, you can replace

plt.legend(b)

with

plt.legend([b])
Related