Adding Legends to Matplotlib Plots
Matplotlib is a powerful Python library for creating visualizations. A crucial element of any good plot is a legend, which helps viewers understand what each line or element represents. This tutorial will guide you through the process of adding legends to your Matplotlib plots effectively.
The Basics: Labeling Your Plots
The foundation of any legend is the label
argument within your plotting functions. When you create a line, scatter plot, or any other graphical element using functions like plt.plot()
, plt.scatter()
, etc., include the label
argument to assign a descriptive name to that element.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sine Wave')
plt.plot(x, y2, label='Cosine Wave')
In this example, we’ve labeled the sine wave and cosine wave plots, which will be used to create the legend.
Displaying the Legend
Once you’ve labeled your plots, you can display the legend using the plt.legend()
function. This function automatically gathers the labels from all plots and presents them in a legend box.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sine Wave')
plt.plot(x, y2, label='Cosine Wave')
plt.legend() # Display the legend
plt.show()
This will generate a plot with a legend explaining which line represents the sine wave and which represents the cosine wave.
Customizing Legend Position
By default, Matplotlib attempts to place the legend in a suitable location. However, you can control the legend’s position using the loc
argument within plt.legend()
. Common options include:
'upper right'
'upper left'
'lower right'
'lower left'
'best'
(let Matplotlib choose the best location)'center'
'center left'
'center right'
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sine Wave')
plt.plot(x, y2, label='Cosine Wave')
plt.legend(loc='upper left') # Place the legend in the upper left corner
plt.show()
Experiment with different loc
values to find the best placement for your specific plot.
Working with Multiple Subplots
When creating plots with multiple subplots, the legend functionality remains the same. Simply label each plot element within its corresponding subplot and then call plt.legend()
to display the legend. The legend will automatically associate the labels with the correct subplots.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# Create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
# Plot on the first subplot
ax1.plot(x, np.sin(x), label='Sine Wave')
ax1.legend()
ax1.set_title('Sine Wave')
# Plot on the second subplot
ax2.plot(x, np.cos(x), label='Cosine Wave')
ax2.legend()
ax2.set_title('Cosine Wave')
plt.tight_layout() # Adjust spacing between subplots
plt.show()
Accessing the Axes Instance
While not strictly necessary for simple plots, you can also access the Axes
instance to manage the legend. This is useful for more complex scenarios or when you need fine-grained control over the legend’s properties. You can get the current axes instance using plt.gca()
.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='Sine Wave')
plt.plot(x, y2, label='Cosine Wave')
ax = plt.gca()
ax.legend()
plt.show()
This approach provides an alternative way to display the legend, and it can be particularly useful when working with multiple subplots or complex plot configurations.