Saturday, October 4, 2025
HomeLanguagesHow to add a title to a Matplotlib legend?

How to add a title to a Matplotlib legend?

Prerequisites: Matplotlib

In this article, we will see how can we can add a title to a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph.

Approach:

  • Import required module.
  • Create data.
  • Add a title to a legend.
  • Normally plot the data.
  • Display plot.

Below is the Implementation:

Example 1:

In this example, we will draw different lines with the help of matplotlib and Use the title argument to plt.legend() to specify the legend title.

Python3




# importing package
import matplotlib.pyplot as plt
import numpy as np
  
# create data
X = [1, 2, 3, 4, 5]
  
# plot lines
plt.plot(X, np.sin(X), label = "Curve-1")
plt.plot(X, np.cos(X), label = "Curve-2")
  
# Add a title to a legend
plt.legend(title = "Legend Title")
plt.title("Line Graph - GeeksforLazyroar")
  
plt.show()


Output:

Example 2:

In this example, we will draw a Bar Graph with the help of matplotlib and Use the title argument to plt.legend() to specify the legend title.

Python3




# importing package
import matplotlib.pyplot as plt
  
# sample code 
plt.bar([1, 2, 3], [16, 4, 1], 
        color ='yellow',
        label = 'Label 2'
  
plt.bar([4, 5], [2, 4], 
        label = 'Label 1')
  
# Add a title to a legend
plt.legend(title = "Variation Rate")
  
plt.title("Line Graph - GeeksforLazyroar")
  
plt.show()


Output:

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32335 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6705 POSTS0 COMMENTS
Nicole Veronica
11870 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11933 POSTS0 COMMENTS
Shaida Kate Naidoo
6821 POSTS0 COMMENTS
Ted Musemwa
7086 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6778 POSTS0 COMMENTS