Adding a legend to a plot in Python is a useful way to label the different elements of the plot and make it easier to understand. In Matplotlib, you can add a legend to a plot using the plt.legend() function.
Here's an example of adding a legend to a plot with two data series:
import matplotlib.pyplot as pltimport numpy as np# Generate some datax = np.linspace(0, 10, 100)y1 = np.sin(x)y2 = np.cos(x)# Create a plot with two data seriesplt.plot(x, y1, label='sin(x)')plt.plot(x, y2, label='cos(x)')# Add a legendplt.legend()# Set the title and axis labelsplt.title('Plot with Legend')plt.xlabel('x')plt.ylabel('y')# Show the plotplt.show() |
In this example, we first generate data for two functions, sine and cosine, using NumPy. We create a plot with two data series using plt.plot() and provide a label for each data series using the label parameter. We then add a legend to the plot using plt.legend(). The plt.legend() function automatically generates a legend using the labels provided for each data series. Finally, we set the title and axis labels using plt.title(), plt.xlabel(), and plt.ylabel(), and display the plot using plt.show().
You can customize the appearance of the legend by passing additional arguments to plt.legend(). For example, you can specify the location of the legend using the loc parameter, change the font size using the fontsize parameter, and change the background color using the facecolor parameter.