create a matplotlib legend in python

To create a legend in matplotlib, first you need to create a plot with multiple lines or bars. Then, call plt.legend() with a list of the label names as arguments. Here's an example code snippet:

main.py
import matplotlib.pyplot as plt

# generate some sample data
x = [0, 1, 2, 3, 4, 5]
y1 = [1, 2, 1, 3, 2, 4]
y2 = [3, 1, 4, 2, 6, 5]

# plot two lines with labels
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')

# add a legend with the label names
plt.legend()

# display the plot
plt.show()
307 chars
17 lines

This code will create a plot with two lines and a legend displaying the labels "Line 1" and "Line 2". You can customize the location of the legend by passing the loc argument to plt.legend(), such as plt.legend(loc='upper left'). There are many other options for customizing the appearance of the legend, such as changing the size or color of the labels.

gistlibby LogSnag