Highlighting date ranges in Matplotlib - Time & Space Complexity
When we highlight date ranges on a plot, we want to know how the time to draw changes as we add more highlights.
How does adding more date ranges affect the work matplotlib does?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import pandas as pd
fig, ax = plt.subplots()
dates = pd.date_range('2024-01-01', periods=100)
values = range(100)
ax.plot(dates, values)
# Highlight 3 date ranges
for start, end in [("2024-01-10", "2024-01-15"), ("2024-01-30", "2024-02-05"), ("2024-02-20", "2024-02-25")]:
ax.axvspan(pd.to_datetime(start), pd.to_datetime(end), color='yellow', alpha=0.3)
plt.show()
This code plots 100 dates and highlights three separate date ranges with colored spans.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over the list of date ranges to add highlight spans.
- How many times: Once per highlighted date range (3 times in this example).
Each additional date range adds one more highlight operation.
| Input Size (number of highlights) | Approx. Operations |
|---|---|
| 3 | 3 highlight calls |
| 10 | 10 highlight calls |
| 100 | 100 highlight calls |
Pattern observation: The work grows directly with the number of highlighted date ranges.
Time Complexity: O(n)
This means the time to add highlights grows linearly with how many date ranges you highlight.
[X] Wrong: "Highlighting many date ranges happens instantly no matter how many."
[OK] Correct: Each highlight adds work, so more highlights take more time to draw.
Understanding how adding visual elements affects performance helps you write efficient plotting code and explain your choices clearly.
What if we changed the code to highlight every single date point instead of ranges? How would the time complexity change?