0
0
Matplotlibdata~5 mins

Highlighting date ranges in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Highlighting date ranges
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

Each additional date range adds one more highlight operation.

Input Size (number of highlights)Approx. Operations
33 highlight calls
1010 highlight calls
100100 highlight calls

Pattern observation: The work grows directly with the number of highlighted date ranges.

Final Time Complexity

Time Complexity: O(n)

This means the time to add highlights grows linearly with how many date ranges you highlight.

Common Mistake

[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.

Interview Connect

Understanding how adding visual elements affects performance helps you write efficient plotting code and explain your choices clearly.

Self-Check

What if we changed the code to highlight every single date point instead of ranges? How would the time complexity change?