Custom Legends with Matplotlib
Last Updated :
07 Dec, 2023
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
Matplotlib - Cursor Widget
Matplotlib is a Data Visualization library in python. It consists of many widgets that are designed to work for any of the GUI backends. Some examples of widgets in matplotlib are Button, CheckButtons, RadioButtons, Cursor, and TextBox. In this article, the Cursor Widget of Matplotlib library has be
2 min read
Matplotlib - Button Widget
In Matplotlib a button is one of the important widgets by which we can perform various operations. They are mostly used for making a good functional graph having different properties. There are three types of buttons ButtonRadio ButtonsCheck Buttons In this article, we will learn how to use differen
4 min read
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 t
12 min read
Matplotlib pyplot.colors()
In Python, we can plot graphs for visualization using the Matplotlib library. For integrating plots into applications, Matplotlib provides an API. Matplotlib has a module named pyplot which provides a MATLAB-like interface. Matplotlib Add ColorThis function is used to specify the color. It is a do-n
2 min read
Line chart in Matplotlib - Python
Matplotlib is a data visualization library in Python. The pyplot, a sublibrary of Matplotlib, is a collection of functions that helps in creating a variety of charts. Line charts are used to represent the relation between two data X and Y on a different axis. In this article, we will learn about lin
6 min read
Introduction to Matplotlib
Matplotlib is a powerful and versatile open-source plotting library for Python, designed to help users visualize data in a variety of formats. Developed by John D. Hunter in 2003, it enables users to graphically represent data, facilitating easier analysis and understanding. If you want to convert y
4 min read
Matplotlib - Checkbox Widget
In this article, We are going to see the use of these checkboxes in matplotlib plots to make our plot more interactive. Checkbox widget offers us the freedom to make our plot more interactive. By using checkboxes we can perform on-tick events which on ticking the checkbox will trigger some event. We
2 min read
Matplotlib.axes.Axes.get_lines() in Python
Matplotlib is a library in Python and it is numerical â mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
2 min read
Matplotlib.figure.Figure() in Python
Matplotlib is a library in Python and it is numerical â mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot
2 min read
Matplotlib.pyplot.autumn() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot,
2 min read