15.1 C
London
Friday, July 5, 2024
HomePythonMatplotlib in PythonHow to Add a Title to Matplotlib Legend (With Examples)

How to Add a Title to Matplotlib Legend (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

By default, legends in Matplotlib plots do not include a title.

However, you can use the following basic syntax to add a title to a legend:

plt.legend(title='this is my title')

The following example shows how to use this syntax in practice.

Example 1: Add Title to Matplotlib Legend

The following code shows how to create a Matplotlib plot with multiple lines and a legend:

import pandas as pd
import matplotlib.pyplot as plt

#create data
df = pd.DataFrame({'points': [11, 17, 16, 18, 22, 25, 26, 24, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4, 8]})

#add lines to plot
plt.plot(df['points'], label='Points')
plt.plot(df['assists'], label='Assists')

#add legend
plt.legend()

Notice that the legend doesn’t have a title.

To add one, we can simply use the title argument within the plt.legend() function:

#add title to legend
plt.legend(title='Metric')

add legend title to Matplotlib plot

To modify the font size of the legend title, use the title_fontsize argument:

Note: The default font size is 10.

#add title to legend with increased font size
plt.legend(title='Metric', title_fontsize=25)

Notice that the font size of the legend is much larger now.

You can also use the fontsize argument to increase the font size of the labels in the legend:

#add title to legend with increased title and label font size
plt.legend(title='Metric', title_fontsize=25, fontsize=15)

Notice that the labels in the legend are much larger now.

Additional Resources

The following tutorials explain how to perform other common operations in Matplotlib:

How to Change Legend Font Size in Matplotlib
How to Change Order of Items in Matplotlib Legend
How to Change the Position of a Legend in Matplotlib

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories