Adding a legend to PyPlot in Matplotlib in the simplest manner possible

Here is a simple code snippet that demonstrates how to add a legend to a PyPlot in Matplotlib:

import matplotlib.pyplot as plt

# Create some data to plot
x = [1, 2, 3, 4]
y = [5, 7, 9, 11]

# Plot the data and label the axes
plt.plot(x, y, label='Data')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Add a legend to the plot
plt.legend()

# Show the plot
plt.show()

Watch a course Python - The Practical Guide

The plt.legend() function is used to add a legend to the plot. The label parameter in the plt.plot() function is used to specify the label for the data that will be displayed in the legend. You can also specify the location of the legend inside the plot by passing loc parameter in the plt.legend() function. plt.legend(loc="upper left")