How to Plot Multiple Lines in Matplotlib: Simple Guide
To plot multiple lines in
matplotlib, call plt.plot() multiple times before plt.show(), or pass multiple sets of x and y data in one plt.plot() call. Each call or data pair creates a new line on the same graph.Syntax
You can plot multiple lines by calling plt.plot() multiple times or by passing multiple x and y pairs in one call.
plt.plot(x1, y1): plots the first lineplt.plot(x2, y2): plots the second lineplt.show(): displays the graph with all lines
Alternatively:
plt.plot(x1, y1, x2, y2): plots two lines in one call
python
import matplotlib.pyplot as plt # Method 1: Multiple plot calls plt.plot([1, 2, 3], [4, 5, 6]) # First line plt.plot([1, 2, 3], [6, 5, 4]) # Second line plt.show()
Example
This example shows how to plot three different lines on the same graph with labels and a legend.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y1 = [1, 4, 9, 16] y2 = [2, 3, 5, 7] y3 = [3, 5, 7, 9] plt.plot(x, y1, label='Squares') plt.plot(x, y2, label='Primes') plt.plot(x, y3, label='Odds') plt.xlabel('X axis') plt.ylabel('Y axis') plt.title('Multiple Lines Example') plt.legend() plt.show()
Output
A line graph with three lines labeled Squares, Primes, and Odds, each showing different y-values over x from 1 to 4.
Common Pitfalls
Common mistakes when plotting multiple lines include:
- Not calling
plt.show()to display the plot. - Using mismatched lengths of x and y data arrays, causing errors.
- Overwriting lines by calling
plt.plot()without holding the previous plots (usually not an issue in matplotlib). - Not adding labels or legends, making it hard to distinguish lines.
python
import matplotlib.pyplot as plt # Wrong: mismatched lengths # plt.plot([1, 2, 3], [4, 5]) # This will cause an error # Right: matching lengths plt.plot([1, 2, 3], [4, 5, 6], label='Line 1') plt.plot([1, 2, 3], [6, 5, 4], label='Line 2') plt.legend() plt.show()
Quick Reference
Tips for plotting multiple lines:
- Use
labelinplt.plot()to name lines. - Call
plt.legend()to show labels. - Use different colors or line styles for clarity.
- Always call
plt.show()to display the plot.
Key Takeaways
Call plt.plot() multiple times or pass multiple data sets to plot multiple lines.
Always use plt.legend() with labels to identify each line clearly.
Ensure x and y data arrays have the same length to avoid errors.
Call plt.show() once after all lines are plotted to display the graph.
Use different colors or styles to make lines easy to distinguish.