0
0
Matplotlibdata~5 mins

Plotting multiple lines in Matplotlib

Choose your learning style9 modes available
Introduction

Plotting multiple lines helps you compare different sets of data on the same graph. It makes it easy to see trends and differences side by side.

Comparing sales of different products over months.
Showing temperature changes in multiple cities over time.
Tracking performance of different students in exams.
Visualizing stock prices of several companies on the same chart.
Syntax
Matplotlib
import matplotlib.pyplot as plt

plt.plot(x1, y1, label='Line 1')
plt.plot(x2, y2, label='Line 2')
...
plt.legend()
plt.show()

Use label to name each line for the legend.

Call plt.legend() to show the labels on the plot.

Examples
Plot two lines with the same x values but different y values.
Matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [1, 3, 5]

plt.plot(x, y1, label='First line')
plt.plot(x, y2, label='Second line')
plt.legend()
plt.show()
Use colors and line styles to make lines different and clear.
Matplotlib
import matplotlib.pyplot as plt

x1 = [0, 1, 2]
y1 = [1, 2, 3]
x2 = [0, 1, 2]
y2 = [3, 2, 1]

plt.plot(x1, y1, 'r-', label='Red line')
plt.plot(x2, y2, 'b--', label='Blue dashed line')
plt.legend()
plt.show()
Sample Program

This program plots sales data for three products over five months. Each product's sales are shown as a separate line with a label. The legend helps identify each line.

Matplotlib
import matplotlib.pyplot as plt

# Data for three lines
months = [1, 2, 3, 4, 5]
sales_A = [10, 15, 20, 25, 30]
sales_B = [12, 18, 22, 28, 35]
sales_C = [8, 14, 19, 23, 29]

# Plot each sales line
plt.plot(months, sales_A, label='Product A')
plt.plot(months, sales_B, label='Product B')
plt.plot(months, sales_C, label='Product C')

# Add labels and title
plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Monthly Sales Comparison')

# Show legend
plt.legend()

# Display the plot
plt.show()
OutputSuccess
Important Notes

Make sure x and y lists have the same length for each line.

You can customize line colors, styles, and markers for clarity.

Always add a legend when plotting multiple lines to avoid confusion.

Summary

Plot multiple lines by calling plt.plot() multiple times.

Use label and plt.legend() to identify lines.

Customize lines with colors and styles to make the graph clear.