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.py307 chars17 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