Matplotlib Legends not working

You should add commas:

plot1, = plt.plot(a,b)
plot2, = plt.plot(a,c)

The reason you need the commas is because plt.plot() returns a tuple of line objects, no matter how many are actually created from the command. Without the comma, "plot1" and "plot2" are tuples instead of line objects, making the later call to plt.legend() fail.

The comma implicitly unpacks the results so that instead of a tuple, "plot1" and "plot2" automatically become the first objects within the tuple, i.e. the line objects you actually want.

http://matplotlib.sourceforge.net/users/legend_guide.html#adjusting-the-order-of-legend-items

line, = plot(x,sin(x)) what does comma stand for?


Use the "label" keyword, like so:

plt.plot(x, y, label='x vs. y')

and then add the legend like so:

plt.legend()

The legend will retain line properties like thickness, colours, etc.

enter image description here


Use handles AKA Proxy artists

import matplotlib.lines as mlines
import matplotlib.pyplot as plt
# defining legend style and data
blue_line = mlines.Line2D([], [], color='blue', label='My Label')
reds_line = mlines.Line2D([], [], color='red', label='My Othes')

plt.legend(handles=[blue_line, reds_line])

plt.show()