Multiple time series comparison in Matplotlib - Time & Space Complexity
When we compare multiple time series using matplotlib, we want to know how the time to draw grows as we add more series or points.
How does adding more lines or data points affect the work matplotlib does?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
n = 1000 # number of points
m = 5 # number of time series
x = np.linspace(0, 10, n)
for i in range(m):
y = np.sin(x + i)
plt.plot(x, y)
plt.show()
This code plots m time series, each with n points, on the same graph.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over m time series, each plotting n points.
- How many times: The plotting function is called m times, each handling n points.
As we add more series or points, the work grows by multiplying these two factors.
| Input Size (n points, m series) | Approx. Operations |
|---|---|
| 10 points, 5 series | 50 |
| 100 points, 5 series | 500 |
| 1000 points, 10 series | 10,000 |
Pattern observation: Doubling points or series roughly doubles the work, so total work grows with both.
Time Complexity: O(m * n)
This means the time to draw grows proportionally with the number of series and the number of points per series.
[X] Wrong: "Adding more series doesn't affect time much because each line is simple."
[OK] Correct: Each series adds a full set of points to draw, so time grows with both series count and points.
Understanding how plotting multiple series scales helps you explain performance in data visualization tasks clearly and confidently.
"What if we used scatter plots instead of line plots for each series? How would the time complexity change?"