Custom Legends with Matplotlib
A legend is an area describing the elements of the graph. In simple terms, it reflects the data displayed in the graph’s Y-axis. It generally appears as the box containing a small sample of each color on the graph and a small description of what this data means.
A Legend can be created using the legend() method. The attribute Loc in the legend() is used to specify the location of the legend. The default value of loc is loc=”best” (upper left). The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure.
Syntax: matplotlib.pyplot.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2)
Example: The attribute bbox_to_anchor=(x, y) of legend() function is used to specify the coordinates of the legend, and the attribute ncol represents the number of columns that the legend has. Its default value is 1.
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
plt.plot(x, y)
plt.plot(y, x)
# Adding the legends
plt.legend(["blue", "orange"])
plt.show()
Output
Refer to the below articles to get detailed information about the legend –
- Matplotlib.pyplot.legend() in Python
- Matplotlib.axes.Axes.legend() in Python
- Change the legend position in Matplotlib
- How to Change Legend Font Size in Matplotlib?
- How Change the vertical spacing between legend entries in Matplotlib?
- Use multiple columns in a Matplotlib legend
- How to Create a Single Legend for All Subplots in Matplotlib?
- How to manually add a legend with a color box on a Matplotlib figure ?
- How to Place Legend Outside of the Plot in Matplotlib?
- How to Remove the Legend in Matplotlib?
- Remove the legend border in Matplotlib
Customizing Styles in Matplotlib
Here, we’ll delve into the fundamentals of Matplotlib, exploring its various classes and functionalities to help you unleash the full potential of your data visualization projects. From basic plotting techniques to advanced customization options, this guide will equip you with the knowledge needed to create stunning visualizations with Matplotlib. So, let’s dive in and discover how to effectively utilize Matplotlib for your data visualization needs.
Table of Content
- Getting Started with Matplotlib
- Exploring Different Plot Styles with Matplotlib
- Matplotlib Figure Class
- Python Pyplot Class
- Matplotlib Axes Class
- Set Colors in Matplotlib
- Add Text, Font and Grid lines in Matplotlib
- Custom Legends with Matplotlib
- Matplotlib Ticks and Tick Labels
- Style Plots using Matplotlib
- Create Multiple Subplots in Matplotlib
- Working With Images In Matplotlib
Contact Us