Custom Legends with Matplotlib
Last Updated :
23 Jul, 2025
In this article, you learn to customize the legend in Matplotlib. matplotlib is a popular data visualization library. It is a plotting library in Python and has its numerical extension NumPy.
What is Legends in Graph?
Legend is an area of the graph describing each part of the graph. A graph can be as simple as it is. But adding the title, X label, Y label, and legend will be more clear. By seeing the names we can easily guess what the graph is representing and what type of data it is representing.
syntax: legend(*args, **kwargs)
This can be called as follows,
legend() -> automatically detects which element to show. It does this by displaying all plots that have been labeled with the label keyword argument.
legend(labels) -> Name of X and name of Y that is displayed on the legend
legend(handles, labels) -> A list of lines that should be added to the legend. Using handles and labels together can give full control of what should be displayed in the legend. The length of the legend and handles should be the same.
Customizing Plot Legends with Matplotlib
Plots on a graph gain insight from legends. The legend is made more readable and recognizable by the addition of the font, origin, and other details. Let's explore the several methods that can be used to change the plot legends.
- Basic Legend with Matplotlib
- Change the Legend Position and Title in Matplotlib
- Change Legend Font Size and Style in Matplotlib
- Change Legend Colors and Background in Matplotlib
- Two line styles in Legend in Matplotlib
- Add Legend to Axes in Matplotlib
- Customizing Legend Labels and Marker Styles in Matplotlib
- Customizing Legend Symbols and Line Width in Matplotlib
- Adding Shadow to Legend Box in Matplotlib
- Creating Colored Markers Legend in Matplotlib
Basic Legend with Matplotlib
Create a simple plot with two curves, these curves, adds labels, displays a legend, and finally shows the legends with Matplotlib.
Python3
import matplotlib.pyplot as plt
import numpy as np
# Example data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels
plt.plot(x, y1, label='Sin(x)')
plt.plot(x, y2, label='Cos(x)')
# Displaying the legend
plt.legend()
# Displaying the plot
plt.show()
Output:

Change the Legend Position and Title in Matplotlib
Matplotlib in Python to create a plot with two curves representing the sine and cosine functions. It customizes the plot by assigning colors to each curve, setting a legend with a title and specific colors, and adding a title to the plot along with labels for the x and y axes.
Location
Sometimes the legend may or may not be in the appropriate place. In matplotlib, we can also add the location where we want to place it. With this flexibility, we can place the legend somewhere where it does not overlay the plots, and hence the plots will look much cleaner and tidier.
Syntax: legend(loc='')
It can be passed as follows,
'upper left', 'upper right', 'lower left', 'lower right' -> It is placed on the corresponding corner of the plot.
'upper center', 'lower center', 'center left', 'center right' -> It is placed on the center of corresponding edge.
'center' -> It is placed exact center of the plot.
'best' -> It is placed without the overlapping of the artists
Title
Adding a title to the legend will be an important aspect to add to the legend box. The title parameter will let us give a title for the legend and the title_size let us assign a specific fontsize for the title.
Syntax:
legend(title=”” , title_fontsize=”)
- title gives title to the legend
- title_fontize gives size to the title.
It can be, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’
Python3
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels and colors
plt.plot(x, y1, label='Sin(x)', color='blue')
plt.plot(x, y2, label='Cos(x)', color='yellow')
# Customizing legend location, title, and colors
plt.legend(loc='upper right', title='Trigonometric Functions', facecolor='lightgrey', labelcolor='black')
# Adding details
plt.title('Sine and Cosine Functions')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Change Legend Font Size and Style in Matplotlib
To make the legend more appealing we can also change the font size of the legend, by passing the parameter font size to the function we can change the fontsize inside the legend box just like the plot titles.
Syntax: legend(fontsize=”)
It can be passed as, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’
Python3
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels and colors
plt.plot(x, y1, label='Sin(x)', color='green', linestyle='--')
plt.plot(x, y2, label='Cos(x)', color='purple', linestyle='-.')
# Customizing font size, style, and colors in the legend
plt.legend(fontsize='large', title_fontsize='x-large', facecolor='lightgrey', labelcolor='black')
# Adding details
plt.title('Sine and Cosine Functions')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Change Legend Colors and Background in Matplotlib
Sometimes we can feel that it would be great if the legend box was filled with some color to make it more attractive and makes the legends stand out from the plots. Matplotlib also covers this by letting us change the theme of the legend by changing the background, text, and even the edge color of the legend.-+
Syntax:
legend(labelcolor=”)
labelcolor is used to change the color of the text.
legend(facecolor=”)
facecolor is used to change background color of the legend.
legend(edgecolor=”)
edgecolor is used to change the edge color of the legend
Python3
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels and colors
plt.plot(x, y1, label='Sin(x)', color='red', linestyle='--')
plt.plot(x, y2, label='Cos(x)', color='blue', linestyle='-.')
# Customizing legend colors, background, and more styling
legend = plt.legend(facecolor='lightgrey', edgecolor='black', fancybox=True, title='Trigonometric Functions', fontsize='large', title_fontsize='x-large')
# Adding details
plt.title('Sine and Cosine Functions')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Two line styles in legend in Matplotlib
The legend is customized using the Line2D
class to create custom legend handles for the different line styles and colors used in the plot. The resulting legend includes a title, as well as labels for the x and y axes, entries for a dashed line and a dash-dot line, each represented by a custom line with a specified color and linestyle.
Python3
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels and vibrant colors
plt.plot(x, y1, label='Sin(x)', linestyle='--', color='teal')
plt.plot(x, y2, label='Cos(x)', linestyle='-.', color='gold')
# Customizing legend handles for different line styles and vibrant colors
custom_lines = [Line2D([0], [0], color='teal', linestyle='--'),
Line2D([0], [0], color='gold', linestyle='-.')]
plt.legend(custom_lines, ['Dashed Line', 'Dash-dot Line'], facecolor='lightgrey', title='Line Styles', fontsize='medium', title_fontsize='large')
# Adding details
plt.title('Sine and Cosine Functions with Line Styles')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Add Legend to Axes in Matplotlib
Custom legend positioned in the upper-right corner with labels for the sine and cosine functions and a title. The overall plot is given a title ('Sine and Cosine Functions in Specific Axes') and labeled x and y axes.
Python3
import matplotlib.pyplot as plt
from matplotlib.legend import Legend
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Creating subplots with gradient colors
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Sin(x)', color='magenta')
line2, = ax.plot(x, y2, label='Cos(x)', color='limegreen')
# Creating a custom legend for a specific subplot with gradient colors
legend_labels = ['Sine Function', 'Cosine Function']
legend = Legend(ax, [line1, line2], legend_labels, loc='upper right', title='Trigonometric Functions', fontsize='large', title_fontsize='x-large')
ax.add_artist(legend)
# Adding details
plt.title('Sine and Cosine Functions in Specific Axes')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Customizing Legend Labels and Marker Styles in Matplotlib
Syntax: legend(markerfirst = bool, default: True)
By default, the marker is placed first and the label is placed second. marker first parameter is used to change the position of the marker. By making it False, the marker and labels places will be swapped.
Python3
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels, different colors, and marker styles
plt.plot(x, y1, label='Sine Function', color='skyblue', marker='o')
plt.plot(x, y2, label='Cosine Function', color='coral', marker='^')
# Customizing legend labels and marker styles
plt.legend(labels=['Sin(x) - Circles', 'Cos(x) - Triangles'], loc='lower right', fontsize='medium')
# Adding details
plt.title('Sine and Cosine Functions with Customized Legends')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Customizing Legend Symbols and Line Width in Matplotlib
The legend is customized to use specific symbols for each line and adjusted line widths. The resulting plot has a title, labels for the x and y axes, and a legend in the upper-right corner with entries for the sine and cosine functions, each indicating its line style and width.
Python3
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels, different colors, and line styles
plt.plot(x, y1, label='Sine Function', color='purple', linestyle='--', linewidth=2)
plt.plot(x, y2, label='Cosine Function', color='orange', linestyle='-', linewidth=2)
# Customizing legend symbols and line widths
plt.legend(handles=plt.gca().lines, labels=['Sin(x) - Dashed', 'Cos(x) - Solid'], loc='upper right', fontsize='medium')
# Adding details
plt.title('Sine and Cosine Functions with Customized Legends')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Adding Shadow to Legend Box in Matplotlib
We can make the legend have some of the basic CSS properties like adding a shadow, adding a frame and making the corners round, and also let us add transparency to the legend box if you don’t want to cover those small details in the plot by a frame.
shadow -> This argument gives shadow behind the legend.
frameon -> Gives the frame to legend.
fancybox -> Gives round edges to the legend.
framealpha -> Gives transparency to legend background.
Python3
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels and different colors
plt.plot(x, y1, label='Sine Function', color='green')
plt.plot(x, y2, label='Cosine Function', color='blue')
# Customizing legend box with shadow
plt.legend(loc='upper left', frameon=True, shadow=True, fontsize='medium')
# Adding details
plt.title('Sine and Cosine Functions with Shadowed Legend Box')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Creating Colored Markers Legend in Matplotlib
The legend is customized to have colored markers corresponding to each curve. The resulting plot has a title, labels for the x and y axes, and a legend in the upper-right corner with entries for the sine and cosine functions, each represented by a marker with a specified color.
Python3
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting with labels, different colors, and marker styles
plt.plot(x, y1, label='Sine Function', color='red', marker='o')
plt.plot(x, y2, label='Cosine Function', color='blue', marker='s')
# Customizing legend with colored markers
legend = plt.legend(loc='upper right', fontsize='medium')
for handle in legend.legendHandles:
handle.set_color('black')
# Adding details
plt.title('Sine and Cosine Functions with Colored Markers in Legend')
plt.xlabel('X values')
plt.ylabel('Y values')
# Displaying the plot
plt.show()
Output:

Similar Reads
Data Science Tutorial Data Science is a field that combines statistics, machine learning and data visualization to extract meaningful insights from vast amounts of raw data and make informed decisions, helping businesses and industries to optimize their operations and predict future trends.This Data Science tutorial offe
3 min read
Introduction to Machine Learning
What is Data Science?Data science is the study of data that helps us derive useful insight for business decision making. Data Science is all about using tools, techniques, and creativity to uncover insights hidden within data. It combines math, computer science, and domain expertise to tackle real-world challenges in a
8 min read
Top 25 Python Libraries for Data Science in 2025Data Science continues to evolve with new challenges and innovations. In 2025, the role of Python has only grown stronger as it powers data science workflows. It will remain the dominant programming language in the field of data science. Its extensive ecosystem of libraries makes data manipulation,
10 min read
Difference between Structured, Semi-structured and Unstructured dataBig Data includes huge volume, high velocity, and extensible variety of data. There are 3 types: Structured data, Semi-structured data, and Unstructured data. Structured data - Structured data is data whose elements are addressable for effective analysis. It has been organized into a formatted repos
2 min read
Types of Machine LearningMachine learning is the branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data and improve from previous experience without being explicitly programmed for every task.In simple words, ML teaches the systems to think and understand like h
13 min read
What's Data Science Pipeline?Data Science is a field that focuses on extracting knowledge from data sets that are huge in amount. It includes preparing data, doing analysis and presenting findings to make informed decisions in an organization. A pipeline in data science is a set of actions which changes the raw data from variou
3 min read
Applications of Data ScienceData Science is the deep study of a large quantity of data, which involves extracting some meaning from the raw, structured, and unstructured data. Extracting meaningful data from large amounts usesalgorithms processing of data and this processing can be done using statistical techniques and algorit
6 min read
Python for Machine Learning
Learn Data Science Tutorial With PythonData Science has become one of the fastest-growing fields in recent years, helping organizations to make informed decisions, solve problems and understand human behavior. As the volume of data grows so does the demand for skilled data scientists. The most common languages used for data science are P
3 min read
Pandas TutorialPandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
6 min read
NumPy Tutorial - Python LibraryNumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens
3 min read
Scikit Learn TutorialScikit-learn (also known as sklearn) is a widely-used open-source Python library for machine learning. It builds on other scientific libraries like NumPy, SciPy and Matplotlib to provide efficient tools for predictive data analysis and data mining.It offers a consistent and simple interface for a ra
3 min read
ML | Data Preprocessing in PythonData preprocessing is a important step in the data science transforming raw data into a clean structured format for analysis. It involves tasks like handling missing values, normalizing data and encoding variables. Mastering preprocessing in Python ensures reliable insights for accurate predictions
6 min read
EDA - Exploratory Data Analysis in PythonExploratory Data Analysis (EDA) is a important step in data analysis which focuses on understanding patterns, trends and relationships through statistical tools and visualizations. Python offers various libraries like pandas, numPy, matplotlib, seaborn and plotly which enables effective exploration
6 min read
Introduction to Statistics
Statistics For Data ScienceStatistics is like a toolkit we use to understand and make sense of information. It helps us collect, organize, analyze and interpret data to find patterns, trends and relationships in the world around us.From analyzing scientific experiments to making informed business decisions, statistics plays a
12 min read
Descriptive StatisticStatistics is the foundation of data science. Descriptive statistics are simple tools that help us understand and summarize data. They show the basic features of a dataset, like the average, highest and lowest values and how spread out the numbers are. It's the first step in making sense of informat
5 min read
What is Inferential Statistics?Inferential statistics is an important tool that allows us to make predictions and conclusions about a population based on sample data. Unlike descriptive statistics, which only summarize data, inferential statistics let us test hypotheses, make estimates, and measure the uncertainty about our predi
7 min read
Bayes' TheoremBayes' Theorem is a mathematical formula used to determine the conditional probability of an event based on prior knowledge and new evidence. It adjusts probabilities when new information comes in and helps make better decisions in uncertain situations.Bayes' Theorem helps us update probabilities ba
13 min read
Probability Data Distributions in Data ScienceUnderstanding how data behaves is one of the first steps in data science. Before we dive into building models or running analysis, we need to understand how the values in our dataset are spread out and thatâs where probability distributions come in.Let us start with a simple example: If you roll a f
8 min read
Parametric Methods in StatisticsParametric statistical methods are those that make assumptions regarding the distribution of the population. These methods presume that the data have a known distribution (e.g., normal, binomial, Poisson) and rely on parameters (e.g., mean and variance) to define the data.Key AssumptionsParametric t
6 min read
Non-Parametric TestsNon-parametric tests are applied in hypothesis testing when the data does not satisfy the assumptions necessary for parametric tests, such as normality or equal variances. These tests are especially helpful for analyzing ordinal data, small sample sizes, or data with outliers.Common Non-Parametric T
5 min read
Hypothesis TestingHypothesis testing compares two opposite ideas about a group of people or things and uses data from a small part of that group (a sample) to decide which idea is more likely true. We collect and study the sample data to check if the claim is correct.Hypothesis TestingFor example, if a company says i
9 min read
ANOVA for Data Science and Data AnalyticsANOVA is useful when we need to compare more than two groups and determine whether their means are significantly different. Suppose you're trying to understand which ingredients in a recipe affect its taste. Some ingredients, like spices might have a strong influence while others like a pinch of sal
9 min read
Bayesian Statistics & ProbabilityBayesian statistics sees unknown values as things that can change and updates what we believe about them whenever we get new information. It uses Bayesâ Theorem to combine what we already know with new data to get better estimates. In simple words, it means changing our initial guesses based on the
6 min read
Feature Engineering
Model Evaluation and Tuning
Data Science Practice