Matplotlib plt.legend() Function: Create Legends for Plots in Python
The plt.legend() function in matplotlib is used to create a legend for a plot. The legend is a box containing a label and a symbol for each line or marker in the plot. It is often used to identify the different data series in a plot.
Here is an example of how to use the plt.legend() function in Python:
import matplotlib.pyplot as plt
# create some data
x = [1, 2, 3, 4]
y1 = [10, 5, 8, 3]
y2 = [6, 8, 4, 2]
# plot the data
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
# add a legend to the plot
plt.legend()
# show the plot
plt.show()
In this example, we first create two sets of data (y1 and y2) and a set of x values (x). We then plot both data sets using the plt.plot() function, giving each line a label using the label parameter. Finally, we call the plt.legend() function to add a legend to the plot. The resulting plot will have a legend box containing the labels 'Line 1' and 'Line 2' with symbols representing each data series.
原文地址: http://www.cveoy.top/t/topic/ojFe 著作权归作者所有。请勿转载和采集!