Before-after comparison plots in Matplotlib - Time & Space Complexity
We want to understand how the time to create before-after comparison plots changes as the amount of data grows.
How does the plotting time increase when we add more points to compare?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
before = [1, 2, 3, 4, 5]
after = [2, 3, 5, 7, 11]
plt.figure(figsize=(6,4))
plt.plot(before, label='Before')
plt.plot(after, label='After')
plt.legend()
plt.show()
This code plots two lines showing values before and after some change for 5 points.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Plotting each data point for both before and after lists.
- How many times: Once for each point in the data arrays (n times per line).
As the number of points increases, the plotting work grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Plot about 20 points (10 before + 10 after) |
| 100 | Plot about 200 points |
| 1000 | Plot about 2000 points |
Pattern observation: Doubling the number of points doubles the plotting work.
Time Complexity: O(n)
This means the time to create the plot grows linearly with the number of data points.
[X] Wrong: "Plotting two lines takes twice as long as plotting one line, so time complexity is O(2n)."
[OK] Correct: Constants like 2 are ignored in time complexity, so O(2n) is simplified to O(n).
Understanding how plotting time grows helps you explain performance when working with bigger datasets in real projects.
"What if we added a loop to create multiple before-after plots for different groups? How would the time complexity change?"