Plotting multiple lines in Matplotlib - Time & Space Complexity
When plotting multiple lines with matplotlib, it's important to understand how the time to draw grows as we add more lines.
We want to know how the plotting time changes when we increase the number of lines.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
for i in range(50):
y = np.sin(x + i)
plt.plot(x, y)
plt.show()
This code plots 50 sine waves, each shifted by a different amount, on the same graph.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that calls
plt.plot()50 times to draw each line. - How many times: Once for each line, so 50 times in this example.
Each additional line adds roughly the same amount of work to draw.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 plot calls |
| 100 | 100 plot calls |
| 1000 | 1000 plot calls |
Pattern observation: The work grows linearly as the number of lines increases.
Time Complexity: O(n)
This means the time to plot grows directly in proportion to the number of lines you draw.
[X] Wrong: "Plotting multiple lines is almost as fast as plotting one line because the data points are the same."
[OK] Correct: Each line requires a separate draw call and rendering, so the time adds up with each new line.
Understanding how plotting time grows helps you write efficient visualization code and explain performance in real projects.
"What if we plotted all lines using a single call with multiple y arrays? How would the time complexity change?"