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?
Practice
plt.axvspan(start_date, end_date) function do in matplotlib?Solution
Step 1: Understand the function purpose
plt.axvspanis used to highlight a vertical area on the plot, usually to mark a range on the x-axis.Step 2: Match parameters to behavior
The parametersstart_dateandend_datedefine the start and end of this vertical span on the x-axis, highlighting that date range.Final Answer:
It highlights a vertical span (date range) on the plot between start_date and end_date. -> Option BQuick Check:
Highlight date range = plt.axvspan(start_date, end_date) [OK]
- Confusing axvspan with line drawing functions
- Thinking it changes axis limits
- Assuming it plots points instead of highlighting
Solution
Step 1: Check parameter names and order
plt.axvspantakes start and end positions as first two arguments, then keyword arguments likecolorandalpha.Step 2: Validate correct keyword for transparency
alphacontrols transparency and should be between 0 and 1. The value 0.5 means 50% transparent.Final Answer:
plt.axvspan('2023-01-01', '2023-01-10', color='red', alpha=0.5) -> Option CQuick Check:
Use alpha for transparency, not transparency keyword [OK]
- Using 'transparency' instead of 'alpha'
- Passing alpha as 50 instead of 0.5
- Using named parameters start= and end= which are invalid
import matplotlib.pyplot as plt
import pandas as pd
dates = pd.date_range('2023-01-01', periods=5)
values = [10, 20, 15, 25, 30]
plt.plot(dates, values)
plt.axvspan(pd.Timestamp('2023-01-02'), pd.Timestamp('2023-01-04'), color='green', alpha=0.3)
plt.show()Solution
Step 1: Understand alpha parameter meaning
Alpha=0.3 means 30% opacity (or 70% transparent), so the color is faint but visible.Step 2: Confirm color and date range
The color is green, and the highlighted range is from Jan 2 to Jan 4 as specified.Final Answer:
A green shaded area with 30% opacity between Jan 2 and Jan 4 -> Option AQuick Check:
alpha=0.3 means 30% opacity, color='green' [OK]
- Confusing alpha as transparency percentage
- Thinking alpha=0.3 means 70% opacity
- Assuming no highlight appears if alpha is low
import matplotlib.pyplot as plt
plt.axvspan('2023-01-01', '2023-01-05', color='blue', alpha=0.4)
plt.show()Solution
Step 1: Check parameter types for axvspan
plt.axvspanexpects numeric or datetime values for start and end. Passing strings directly causes errors.Step 2: Correct usage for dates
Convert strings to datetime objects usingpd.Timestampordatetimebefore passing.Final Answer:
Dates are passed as strings; they should be converted to datetime objects. -> Option AQuick Check:
axvspan needs datetime, not string dates [OK]
- Passing date strings directly without conversion
- Misusing alpha as integer
- Wrong color parameter spelling
Solution
Step 1: Identify weekend dates in the range
Loop through each date, check if it is Saturday (weekday=5) or Sunday (weekday=6).Step 2: Highlight each weekend separately
Useplt.axvspanfor each weekend day or range with desired color and transparency.Step 3: Understand why other options fail
Use plt.axvspan once with start='2023-01-01' and end='2023-01-31' and color='gray', alpha=0.2. highlights entire month, not weekends. Plot vertical lines on weekends using plt.axvline with color='gray' and alpha=0.2. draws lines, not spans. Use plt.fill_between with weekend dates and color='gray', alpha=0.2. is for y-axis fills, not x-axis spans.Final Answer:
Loop through dates, check if weekday is Saturday or Sunday, then use plt.axvspan for each weekend with color='gray' and alpha=0.2. -> Option DQuick Check:
Highlight weekends individually with axvspan [OK]
- Highlighting entire date range instead of weekends
- Using axvline instead of axvspan for spans
- Trying to fill y-axis area instead of x-axis date range
Ready to prove it?
Pass the test and this pattern moves unknown
