Time series with fill_between in Matplotlib - Time & Space Complexity
When plotting time series with shaded areas using fill_between, it is important to understand how the plotting time grows as the data size increases.
We want to know how the number of points affects the time matplotlib takes to draw the plot.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
time = np.arange(0, 1000)
values = np.sin(time * 0.01)
plt.plot(time, values)
plt.fill_between(time, values - 0.1, values + 0.1, alpha=0.3)
plt.show()
This code plots a time series and shades the area around the line using fill_between.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over each point in the time array to draw the line and fill the area.
- How many times: Once for each of the n points in the time series.
As the number of points increases, matplotlib processes each point to draw lines and fill areas, so the work grows with the number of points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations to draw and fill |
| 100 | About 100 operations to draw and fill |
| 1000 | About 1000 operations to draw and fill |
Pattern observation: The operations increase roughly in direct proportion to the number of points.
Time Complexity: O(n)
This means the time to plot grows linearly with the number of data points.
[X] Wrong: "Adding fill_between does not affect the plotting time much because it just colors the area."
[OK] Correct: fill_between processes every point to create the shaded area, so it adds work proportional to the data size.
Understanding how plotting time grows with data size helps you write efficient visualization code and explain performance in real projects.
"What if we used fewer points but more fill_between calls? How would the time complexity change?"