Python | Adding legend to a Plot

Python | Adding legend to a Plot: In this article, we are going to learn about adding legend to a plot and its Python implementation.
Submitted by Anuj Singh, on July 11, 2020

Adding legend is the best way to label data series plotted on a graph. Matplotlib has an inbuilt defined function for our adding legend operation. The legend can be added to any type of plot such as line plot, dot plot, scatter plot, bar plot, etc. Following are some examples showing the implementation of matplotlib.pyplot.legend().

Python | Adding legend to a Plot (1)

Python | Adding legend to a Plot (2)

Python | Adding legend to a Plot (3)

References: https://matplotlib.org/, https://in.mathworks.com/

Python code for adding legend to a plot

# Data Visualization using Python
# Adding a Legend

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2, 100)

# Example 1
plt.figure()
plt.plot(x, x+2, label='linear')  
plt.plot(x, x**2, label='quadratic')  
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Legend Example 1")
plt.legend()

# Example 2
plt.figure()
x = np.linspace(0.0, 5.0)
y = x*x
plt.subplot(2, 1, 2)
plt.plot(x, y, 'g.-',label='quadratic')
plt.plot(x,x, 'r.-', label='linear')
plt.title('Legend Example 2')
plt.xlabel('numbers')
plt.ylabel('Square')
plt.legend()
plt.show()

# Example 3
# Random Bar Graph Example
plt.figure()
plt.barh(np.arange(26), np.random.randint(0,50,26), alpha = 0.5, color='r', label='Legend Bar Graph')
plt.title('Horizontal Bar Graph : Random')
plt.legend()

Output:

Output is as figure





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.