Waterfall chart pattern in Matplotlib - Time & Space Complexity
We want to understand how the time to draw a waterfall chart changes as the data size grows.
How does the number of steps affect the work matplotlib does to build the chart?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
values = [100, -30, 20, -10, 40]
cumulative = [0]
for v in values:
cumulative.append(cumulative[-1] + v)
plt.bar(range(len(values)), values, bottom=cumulative[:-1])
plt.show()
This code builds a simple waterfall chart by stacking bars based on cumulative sums.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over the list of values to compute cumulative sums and draw bars.
- How many times: Once for each value in the input list.
Each new data point adds one more bar and one more cumulative sum calculation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 cumulative sums and 10 bars drawn |
| 100 | About 100 cumulative sums and 100 bars drawn |
| 1000 | About 1000 cumulative sums and 1000 bars drawn |
Pattern observation: The work grows directly with the number of data points.
Time Complexity: O(n)
This means the time to create the waterfall chart grows in a straight line as the data size increases.
[X] Wrong: "Drawing a waterfall chart takes the same time no matter how many bars there are."
[OK] Correct: Each bar requires calculations and drawing steps, so more bars mean more work.
Understanding how chart drawing time grows helps you explain performance in data visualization tasks clearly and confidently.
What if we added nested loops to compare each bar with every other bar? How would the time complexity change?