Legends - ( Matplotlib Plots )
Heading h2
Syntax
ax.legend(loc=0, frameon=True, fontsize='small')
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y1, label='sin(x)')
ax.plot(x, y2, label='cos(x)')
ax.legend(loc=0, frameon=True, fontsize='small')
Output
A plot with two lines, each with its own label and a legend with a box around it located in the upper left corner of the plot.
Explanation
In data visualization, the legend is an essential component that informs the audience about the different lines or elements in a plot. Matplotlib provides a built-in function, legend()
, that generates a legend automatically based on the labels assigned to each line or plot element.
In the above example, we create a plot with two lines: sin(x)
and cos(x)
. We also label each line using the label
parameter in the plot()
function. Finally, we call the legend()
function on the ax
object to generate a legend in the upper left corner of the plot with a box around it.
Use
The legend()
function in Matplotlib is useful when creating multiple lines or elements on a plot to explain the meaning of each element or line. It can accept several parameters that allow for customization of the legend's appearance, such as the fontsize
, frameon
, and loc
parameters.
Important Points
- The
legend()
function in Matplotlib generates a legend for a plot based on the labels assigned to each line or plot element. - The function has several parameters that allow for customization of the legend's appearance, such as
fontsize
,frameon
, andloc
. - Legends are crucial for explaining the meaning of different lines or elements in a visualization.
Summary
In conclusion, the legend()
function in Matplotlib is a useful tool for creating legends that explain the meaning of different lines or elements in a visualization. By providing labels to each line or element, users can ensure that their audience understands the message portrayed in the plot. The function also accepts parameters that allow for customization of the legend's appearance to improve readability and accessibility.