Legends and Multiple Lines
What You'll Learn
You'll learn how to plot multiple data series on the same axes and use legends to clearly distinguish between them.
Why Plot Multiple Lines?
When you need to compare trends or patterns across different groups, categories, or variables, plotting them together on one set of axes makes comparison intuitive. However, without proper labeling, viewers won't know which line represents what—this is where legends become essential.
Adding Multiple Lines
In Matplotlib, you can call plt.plot() multiple times before displaying the figure. Each call adds another line to the same axes:
import matplotlib.pyplot as plt
# Plotting three different series
plt.plot([1, 2, 3, 4], [1, 4, 2, 3], label='Product A')
plt.plot([1, 2, 3, 4], [2, 3, 4, 5], label='Product B')
plt.plot([1, 2, 3, 4], [3, 2, 1, 4], label='Product C')
Notice the label parameter—this assigns a name to each line.
Creating the Legend
To display the legend, simply call:
plt.legend()
Matplotlib automatically creates a legend box showing each line's color/style alongside its label. You can control legend placement with the loc parameter (e.g., loc='upper right', loc='best').
Putting It Together
plt.plot([1, 2, 3, 4], [1, 4, 2, 3], label='Product A')
plt.plot([1, 2, 3, 4], [2, 3, 4, 5], label='Product B')
plt.xlabel('Quarter')
plt.ylabel('Sales')
plt.title('Quarterly Sales Comparison')
plt.legend()
plt.show()
Think of legends as a decoder ring for your visualization—without them, multiple lines create confusion rather than clarity.
Key Takeaway: Use label parameters when plotting multiple series and call plt.legend() to automatically generate a legend that helps viewers distinguish between lines.