Area chart with plt.fill_between in Matplotlib - Time & Space Complexity
We want to understand how the time to draw an area chart changes as we add more data points.
How does the drawing time grow when the data size grows?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 1000)
y1 = np.sin(x)
y2 = np.sin(x) + 1
plt.fill_between(x, y1, y2)
plt.show()
This code draws an area chart by filling the space between two curves defined by y1 and y2 over x.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over the data points in arrays x, y1, and y2 to fill the area.
- How many times: Once for each data point, so as many times as the length of x (here 1000).
As the number of data points increases, the number of operations to fill the area grows roughly the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 fill steps |
| 100 | About 100 fill steps |
| 1000 | About 1000 fill steps |
Pattern observation: The work grows linearly as the number of points increases.
Time Complexity: O(n)
This means the time to draw the area grows directly in proportion to the number of data points.
[X] Wrong: "Adding more points won't affect drawing time much because it's just one fill call."
[OK] Correct: The fill_between function processes each data point to create the filled area, so more points mean more work.
Understanding how plotting functions scale with data size helps you write efficient code and explain performance clearly.
"What if we used fewer points but more complex shapes? How would the time complexity change?"