Add a Matplotlib Legend in a Graph

A legend in a graph is a box on the left and right displaying the data from the columns. Legend generally helps the readers understand the graph. Before moving further, we’ve prepared a video tutorial to add a Matplotlib Legend in a Graph:

Here is what a legend looks like in a graph:

Legend in Matplotlib

The legend() function is used to create a legend in Matplotlib.

Let us now see a complete example of legends in a graph in Matplotlib. We have plotted the frequencies of a signal in this example:

import numpy as np
import matplotlib.pyplot as plt

# Data
a = np.arange(5)
b = [2,4,6,8,10]
c = [5, 6, 7, 8, 9]

# Create plots
fig = plt.figure()
ax = plt.subplot()
ax.plot(a, b, 'k--', label='Frequency')
ax.plot(a, c, 'k:', label='Periods')

# Create a legend using the Matplotlib Axes.legend() method in Python
ax.legend()

# Plot Title
plt.title("Frequency of a Signal")

# Display
plt.show()

OutputAdd a Matplotlib Legend in a Graph


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Matplotlib - Histogram
Position Matplotlib Legends
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment