How to Add Legends to A Matplotlib Plot?

10 minutes read

Adding legends to a matplotlib plot is a useful way to label the different elements or data series in a plot. A legend can provide context and make it easier to interpret the chart. Here is how you can add a legend to a matplotlib plot:

  1. Import the necessary library:
1
import matplotlib.pyplot as plt


  1. Create your plot using the plt.plot() function or any other plotting function from matplotlib.
  2. Assign labels to each data series or element you want to include in the legend. This can be done by passing a label parameter to the plotting function for each data series:
1
2
plt.plot(x, y1, label='Data Series 1')
plt.plot(x, y2, label='Data Series 2')


  1. After plotting all the data series, call the plt.legend() function. By default, it will create a legend using the labels defined earlier:
1
plt.legend()


  1. Optionally, you can customize the position and appearance of the legend by passing additional parameters to plt.legend(). For example, you can specify the location of the legend using the loc parameter:
1
plt.legend(loc='upper right')


Here are a few examples of available loc values: 'best', 'upper right', 'upper left', 'lower left', 'lower right', 'center', 'center left', 'center right', 'right', 'upper center', 'lower center'.


You can also control other properties of the legend, such as the title or the background color, by passing additional arguments to plt.legend().

  1. When you are finished customizing your plot, call plt.show() to display the plot with the legend.


Make sure to include these steps in your code to add legends to your matplotlib plots effectively.

Best Matplotlib Books to Read in 2024

1
Data Visualization in Python with Pandas and Matplotlib

Rating is 5 out of 5

Data Visualization in Python with Pandas and Matplotlib

2
Matplotlib 3.0 Cookbook: Over 150 recipes to create highly detailed interactive visualizations using Python

Rating is 4.9 out of 5

Matplotlib 3.0 Cookbook: Over 150 recipes to create highly detailed interactive visualizations using Python

3
Matplotlib for Python Developers

Rating is 4.8 out of 5

Matplotlib for Python Developers

4
Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib

Rating is 4.7 out of 5

Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib

5
Matplotlib 2.x By Example: Multi-dimensional charts, graphs, and plots in Python

Rating is 4.6 out of 5

Matplotlib 2.x By Example: Multi-dimensional charts, graphs, and plots in Python

6
Matplotlib for Python Developers: Effective techniques for data visualization with Python, 2nd Edition

Rating is 4.5 out of 5

Matplotlib for Python Developers: Effective techniques for data visualization with Python, 2nd Edition

7
Python Data Analytics: With Pandas, NumPy, and Matplotlib

Rating is 4.4 out of 5

Python Data Analytics: With Pandas, NumPy, and Matplotlib

8
Python and Matplotlib Essentials for Scientists and Engineers (Iop Concise Physics)

Rating is 4.3 out of 5

Python and Matplotlib Essentials for Scientists and Engineers (Iop Concise Physics)

9
Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization, 2nd Edition

Rating is 4.2 out of 5

Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization, 2nd Edition

10
Data Visualization with Python for Beginners: Visualize Your Data using Pandas, Matplotlib and Seaborn (Machine Learning & Data Science for Beginners)

Rating is 4.1 out of 5

Data Visualization with Python for Beginners: Visualize Your Data using Pandas, Matplotlib and Seaborn (Machine Learning & Data Science for Beginners)


What is the purpose of legends in Matplotlib plots?

The purpose of legends in Matplotlib plots is to provide a textual description or explanation of the elements present in the plot. Legends help in identifying the different data series or groups represented in the plot, especially when multiple elements or categories are plotted together. It allows the viewer to understand the meaning or interpretation of the different colors, shapes, or markers used in the plot. Legends are particularly useful in different types of plots, such as line plots, scatter plots, or bar plots, where multiple data series or groups are visualized in a single plot.


How to change the font size of a legend in Matplotlib?

To change the font size of a legend in Matplotlib, you can use the fontsize parameter in the plt.legend() function. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import matplotlib.pyplot as plt

# Generate some data
x = [1, 2, 3]
y = [4, 5, 6]

# Scatter plot
plt.scatter(x, y, label='Data')

# Create legend
legend = plt.legend(fontsize='large')

# Show the plot
plt.show()


In this example, fontsize='large' is used to set the font size of the legend to a larger size. You can also set it to other values like 'small', 'medium', or a numeric value like 10.


What is the difference between a legend and a key in Matplotlib?

In Matplotlib, a legend and a key serve similar purposes of providing additional information about the plot elements. However, there are some differences between the two:

  1. Definition: A legend is a box or area on the plot that displays symbolic representations (e.g., colored lines, markers, etc.) and their respective labels, indicating what each element represents. On the other hand, a key is a single feature on the plot that represents an aspect of the visual representation (e.g., color, marker, linetype, etc.) and its corresponding meaning.
  2. Usage: A legend is commonly used when there are multiple elements in a plot, each with a unique label. It helps in identifying and understanding the elements based on their labels. A key, on the other hand, is primarily used to explain the meaning of various visual properties or styles used in the plot, such as color coding or line types.
  3. Appearance: A legend is typically displayed as a separate box or area within the plot, often placed at a corner or a specified position. It contains the labels and corresponding symbols or representations associated with the plot elements. A key, on the other hand, is a single representative feature on the plot, such as a colored line or a marker, accompanied by a label or text explaining its meaning.


In summary, a legend is used to display and explain multiple plot elements with their respective labels, while a key represents a single visual property or style and its corresponding meaning.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To add a title to a Matplotlib plot, you can use the title() function provided by Matplotlib. The title can provide a brief description or name for the plot, which helps in understanding the visual representation of the data.Here is an example of how to add a ...
To plot data from a Pandas DataFrame with Matplotlib, you can follow these steps:Import the required libraries: import pandas as pd import matplotlib.pyplot as plt Load or create a Pandas DataFrame with data that you want to plot. Decide on the type of plot yo...
To add a plot to a figure in Matplotlib, you can follow these steps:Import the necessary libraries: import matplotlib.pyplot as plt import numpy as np Create a figure and an axis: fig, ax = plt.subplots() Generate some data points to plot: x = np.linspace(0, 1...