Home »
Python »
Python Data Visualization
Python | Adding legend to a Plot
Python | Adding legend to a Plot: In this tutorial, we will learn about adding legend to a plot and its Python implementation.
By Anuj Singh Last updated : August 18, 2023
Adding legend to a Plot
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().
Examples
Python program 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
References: https://matplotlib.org/, https://in.mathworks.com/