Matplotlib Pyplot Legend
What is Matplotlib Pyplot Legend?
A matplotlib legend is a small box that describes the various elements of the plot in terms of lines and markers that have distinct styles or colors. It is especially important for plots with two or more data series: it makes it possible to visually separate one series from another. A legend usually displays a list of labels: each one represents an element in the plot, such as a line or marker, with possibly an optional description of the line or marker style.
The Pyplot Legend applies specifically to Matplotlib's pyplot interface (commonly imported as "plt"). With this interface, Python enjoys MATLAB-like plotting.
Why Use Legends in Matplotlib?
Legends are relevant in any visualization because they are used to:
- Promote Readability: With multiple lines or elements, a plot can thus allow its viewer to easily understand what each line or marker stands for.
- Advance Clarity: Legends help provide contextual meaning to various graph elements, especially in scientific and data-driven plots.
- Inject Professionalism: Well-placed and clear legends increase both the plot's visual elegance and professionalism, making them easier for the audience to understand.
Basic Syntax to Add a Legend
The matplotlib legend is quite easy to add. Fret not; with a few commands in the legend method, drawing a legend onto your plot is as easy as putting on your shoes. The syntax gives basic commands to the canvas to display the names of the elements you want in it.
An example is as follows that should provide you with a simple way to put a legend on the plot:
Example 1: Basic Legend
#matplotlib legend
import matplotlib.pyplot as plt
# Data for plotting
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]
# Plot the data
plt.plot(x, y1, label="y = x^2") # Label for the first line
plt.plot(x, y2, label="y = x + 1") # Label for the second line
# Adding a legend
plt.legend()
# Display the plot
plt.show()
Output Explanation:
- The label parameter of the plt.plot() function describes the text that will be put into the legend for each line.
- The automatic generation of the legend with the labels provided in the plot() calls is by the function plt.legend().
- plt.show() displays the plot.
Running that code will give you a plot of two lines representing the equations y=x^2 and y=x+1, with the legend giving corresponding identification to the two lines.
Customizing the Legend
These default matplotlib legends are typically satisfactory, but there exist many possibilities to customize the legend for appearance and position. Let's take a look at some of the most practical customization options available for Matplotlib legends.
1. Positioning the Legend
By default, matplotlib will place the legend in the best position-typically in the upper-left corner of the plot. However, you can specify the location of the legend by passing parameters for loc in the plt.legend() function.
Example 2: Changing the Legend Position
import matplotlib.pyplot as plt
# Data for plotting
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]
# Plot the data
plt.plot(x, y1, label="y = x^2")
plt.plot(x, y2, label="y = x + 1")
# Move the legend to the upper right
plt.legend(loc='upper right')
# Display the plot
plt.show()
The loc
parameter can take a variety of values:
'upper left'
'upper right'
'lower left'
'lower right'
'center'
You can also specify the location of the legend by giving values based on numerical numbers (for example, loc=1 representing the upper right corner, loc=2 representing the upper left corner).
2. Customizing Legend Fonts and Styles
You can opt to alter the font properties of the matplotlib legend to give it more visibility. Fontsize parameter allows you to set font size or font weight to the pltlegend() function as arguments.
Example 3: Customizing Font Style
import matplotlib.pyplot as plt
# Data for plotting
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]
# Plot the data
plt.plot(x, y1, label="y = x^2")
plt.plot(x, y2, label="y = x + 1")
# Customize the legend font
plt.legend(fontsize='x-large', loc='upper left')
# Display the plot
plt.show()
This will embed the font of the legend with an increasing size-"x-large."
3. Adding Legend Title
In cases where multiple categories are included in the legend or in complex plots, a legend title can be very useful. You can do this with the title parameter to add a title to the legend.
Example 4: Adding a Legend Title
import matplotlib.pyplot as plt
# Data for plotting
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]
# Plot the data
plt.plot(x, y1, label="y = x^2")
plt.plot(x, y2, label="y = x + 1")
# Adding a title to the legend
plt.legend(title="Functions", loc='upper left')
# Display the plot
plt.show()
In this example, the legend title "Functions" will appear at the top of the legend box.
4. Adjusting the Legend Box
It is possible to change the background color and edge color of the matplotlib legend box. This is handy when you want to improve the visual clarity of the legend, especially when several overlapping colors are present.
Example 5: Customizing the Legend Box
import matplotlib.pyplot as plt
# Data for plotting
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]
# Plot the data
plt.plot(x, y1, label="y = x^2")
plt.plot(x, y2, label="y = x + 1")
# Customizing the legend box
plt.legend(frameon=True, facecolor='lightgray', edgecolor='black')
# Display the plot
plt.show()
In this case, the legend box will have a light gray background with a black border.
5. Multiple Legends
In some cases, you might need multiple legends for different parts of the plot. Matplotlib allows you to create multiple legends by calling the legend() function repeatedly.
Example 6: Multiple Legends
import matplotlib.pyplot as plt
# Data for plotting
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]
y3 = [1, 2, 3, 4]
# Plot the data
plt.plot(x, y1, label="y = x^2")
plt.plot(x, y2, label="y = x + 1")
plt.plot(x, y3, label="y = x")
# Adding the first legend
plt.legend(loc='upper left')
# Adding a second legend
plt.plot(x, y1, linestyle='--', label="y = x^2 (dashed)")
plt.legend(loc='lower right')
# Display the plot
plt.show()
This code adds two legends to the plot, one in the upper left and another in the lower right.
Conclusion
The pyplot.legend() function from Matplotlib is one of the important methods to enhance clarity in your visualizations. Legends separate multiple data series and therefore enhance the information value of plots. There are different customization options—position, font style, box color, and even multiple legends—that will assist you in giving your plot the appearance you want.
Working with legends and stylistically customizing them is a great skill for any data visualization task. Following the examples and tips given in this blog should help you enhance the readability and professional look of your plots, making them easier to read and more useful for the audience.