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.
Practice
(1/5)
1. What is the main way to plot multiple lines on the same graph using matplotlib?
easy
A. Use plt.hist() multiple times
B. Use plt.scatter() for each line
C. Call plt.plot() multiple times with different data sets before plt.show()
D. Call plt.bar() for each line
Solution
Step 1: Understand plotting multiple lines
In matplotlib, to plot multiple lines on the same graph, you call plt.plot() for each line's data before showing the plot.
Step 2: Identify correct plotting function
plt.scatter(), plt.bar(), and plt.hist() are for scatter plots, bar charts, and histograms, not line plots.
Final Answer:
Call plt.plot() multiple times with different data sets before plt.show() -> Option C
Quick Check:
Multiple plt.plot() calls = multiple lines [OK]
Hint: Use multiple plt.plot() calls to add lines [OK]
Common Mistakes:
Using plt.scatter() instead of plt.plot() for lines
Calling plt.show() after each line instead of once
Using bar or histogram functions for line plots
2. Which of the following code snippets correctly plots two lines on the same graph?