How to add a title to a Matplotlib legend?
Last Updated :
24 Jan, 2021
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
import matplotlib.pyplot as plt
import numpy as np
X = [ 1 , 2 , 3 , 4 , 5 ]
plt.plot(X, np.sin(X), label = "Curve-1" )
plt.plot(X, np.cos(X), label = "Curve-2" )
plt.legend(title = "Legend Title" )
plt.title( "Line Graph - Geeksforgeeks" )
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
import matplotlib.pyplot as plt
plt.bar([ 1 , 2 , 3 ], [ 16 , 4 , 1 ],
color = 'yellow' ,
label = 'Label 2' )
plt.bar([ 4 , 5 ], [ 2 , 4 ],
label = 'Label 1' )
plt.legend(title = "Variation Rate" )
plt.title( "Line Graph - Geeksforgeeks" )
plt.show()
|
Output:
Share your thoughts in the comments
Please Login to comment...