Legends and colorbars help people understand what different colors or symbols mean in a chart. They make reading graphs easier and clearer.
0
0
Why legends and colorbars guide reading in Matplotlib
Introduction
When you have multiple lines or points with different colors or shapes in a plot.
When you use colors to show different values or categories in a heatmap or scatter plot.
When you want to explain what each color or symbol represents in your data visualization.
Syntax
Matplotlib
plt.legend(label_list) plt.colorbar(mappable)
plt.legend() adds a box explaining symbols or colors used in the plot.
plt.colorbar() adds a scale showing how colors map to data values.
Examples
This adds a legend showing 'Line 1' and 'Line 2' for the two lines.
Matplotlib
plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2') plt.legend()
This adds a colorbar next to the heatmap to explain the color scale.
Matplotlib
im = plt.imshow(data, cmap='viridis')
plt.colorbar(im)Sample Program
This code draws two lines with a legend to explain them. It also shows a heatmap with a colorbar to explain the colors.
Matplotlib
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) plt.plot(x, y1, label='Sine wave') plt.plot(x, y2, label='Cosine wave') plt.legend() # Create a heatmap np.random.seed(0) data = np.random.rand(10, 10) im = plt.imshow(data, cmap='plasma') plt.colorbar(im) plt.title('Line plot with legend and heatmap with colorbar') plt.show()
OutputSuccess
Important Notes
Always add legends or colorbars when your plot uses colors or symbols to represent different data.
Legends help identify categories, colorbars help understand continuous values.
Without them, your audience might get confused about what the colors or symbols mean.
Summary
Legends explain what different lines or symbols mean in a plot.
Colorbars show how colors relate to data values in heatmaps or similar plots.
Using them makes your charts easier to read and understand.