Bird
Raised Fist0
Matplotlibdata~20 mins

Highlighting date ranges in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Date Range Highlighting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of date range highlighting with matplotlib
What will be the output of this code snippet that highlights a date range on a line plot?
Matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

dates = pd.date_range('2024-01-01', periods=10)
values = np.arange(10)

plt.plot(dates, values)
plt.axvspan(pd.Timestamp('2024-01-03'), pd.Timestamp('2024-01-06'), color='yellow', alpha=0.3)
plt.show()
AA line plot with a yellow transparent vertical band from Jan 3 to Jan 6
BA line plot with a red transparent vertical band from Jan 1 to Jan 10
CA line plot with no highlighted area
DA line plot with a yellow transparent horizontal band from 3 to 6
Attempts:
2 left
💡 Hint
Look at the function plt.axvspan and the dates it uses.
❓ data_output
intermediate
1:30remaining
Number of points inside highlighted date range
Given the following data and highlighted date range, how many data points fall inside the highlighted range?
Matplotlib
import pandas as pd
import numpy as np

dates = pd.date_range('2024-01-01', periods=15)
values = np.random.rand(15)
data = pd.DataFrame({'date': dates, 'value': values})
highlight_start = pd.Timestamp('2024-01-05')
highlight_end = pd.Timestamp('2024-01-10')

inside_points = data[(data['date'] >= highlight_start) & (data['date'] <= highlight_end)]
print(len(inside_points))
A6
B5
C7
D10
Attempts:
2 left
💡 Hint
Count dates from Jan 5 to Jan 10 inclusive.
❓ visualization
advanced
2:30remaining
Identify the correct highlighted date range in plot
Which option shows the correct code to highlight the date range from 2024-02-10 to 2024-02-15 on a time series plot?
Matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

dates = pd.date_range('2024-02-01', periods=20)
values = np.random.randn(20).cumsum()
plt.plot(dates, values)
# Highlight code here
plt.show()
A
plt.axvline(pd.Timestamp('2024-02-10'), color='green')
plt.axvline(pd.Timestamp('2024-02-15'), color='green')
Bplt.axhspan(pd.Timestamp('2024-02-10'), pd.Timestamp('2024-02-15'), color='green', alpha=0.2)
Cplt.axvspan(pd.Timestamp('2024-02-10'), pd.Timestamp('2024-02-15'), color='green', alpha=0.2)
Dplt.fill_between(dates, values, where=(dates >= '2024-02-10') & (dates <= '2024-02-15'), color='green', alpha=0.2)
Attempts:
2 left
💡 Hint
Use vertical span to highlight date ranges on x-axis.
🔧 Debug
advanced
2:00remaining
Identify the error in date range highlighting code
What error will this code produce when trying to highlight a date range?
Matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

dates = pd.date_range('2024-03-01', periods=10)
values = np.arange(10)
plt.plot(dates, values)
plt.axvspan('2024-03-03', '2024-03-06', color='blue', alpha=0.3)
plt.show()
ATypeError: unsupported operand type(s) for -: 'str' and 'str'
BNo error, plot shows highlighted range correctly
CNameError: name 'pd' is not defined
DValueError: could not convert string to float: '2024-03-03'
Attempts:
2 left
💡 Hint
Check the types passed to plt.axvspan for date values.
🚀 Application
expert
3:00remaining
Calculate total duration of multiple highlighted date ranges
Given multiple highlighted date ranges, what is the total number of days covered without counting overlaps twice?
Matplotlib
import pandas as pd

ranges = [
    (pd.Timestamp('2024-04-01'), pd.Timestamp('2024-04-05')),
    (pd.Timestamp('2024-04-04'), pd.Timestamp('2024-04-10')),
    (pd.Timestamp('2024-04-12'), pd.Timestamp('2024-04-15'))
]

# Calculate total days covered by these ranges without double counting overlaps
A15
B14
C12
D13
Attempts:
2 left
💡 Hint
Merge overlapping intervals before summing durations.

Practice

(1/5)
1. What does the plt.axvspan(start_date, end_date) function do in matplotlib?
easy
A. It draws a horizontal line at start_date.
B. It highlights a vertical span (date range) on the plot between start_date and end_date.
C. It creates a scatter plot of dates between start_date and end_date.
D. It sets the x-axis limits to start_date and end_date.

Solution

  1. Step 1: Understand the function purpose

    plt.axvspan is used to highlight a vertical area on the plot, usually to mark a range on the x-axis.
  2. Step 2: Match parameters to behavior

    The parameters start_date and end_date define the start and end of this vertical span on the x-axis, highlighting that date range.
  3. Final Answer:

    It highlights a vertical span (date range) on the plot between start_date and end_date. -> Option B
  4. Quick Check:

    Highlight date range = plt.axvspan(start_date, end_date) [OK]
Hint: Remember axvspan highlights vertical areas between two x-values [OK]
Common Mistakes:
  • Confusing axvspan with line drawing functions
  • Thinking it changes axis limits
  • Assuming it plots points instead of highlighting
2. Which of the following is the correct syntax to highlight the date range from '2023-01-01' to '2023-01-10' with a semi-transparent red color in matplotlib?
easy
A. plt.axvspan(start='2023-01-01', end='2023-01-10', color='red', alpha=0.5)
B. plt.axvspan('2023-01-01', '2023-01-10', color='red', transparency=0.5)
C. plt.axvspan('2023-01-01', '2023-01-10', color='red', alpha=0.5)
D. plt.axvspan('2023-01-01', '2023-01-10', alpha=50, color='red')

Solution

  1. Step 1: Check parameter names and order

    plt.axvspan takes start and end positions as first two arguments, then keyword arguments like color and alpha.
  2. Step 2: Validate correct keyword for transparency

    alpha controls transparency and should be between 0 and 1. The value 0.5 means 50% transparent.
  3. Final Answer:

    plt.axvspan('2023-01-01', '2023-01-10', color='red', alpha=0.5) -> Option C
  4. Quick Check:

    Use alpha for transparency, not transparency keyword [OK]
Hint: Use alpha (0-1) for transparency, not transparency keyword [OK]
Common Mistakes:
  • Using 'transparency' instead of 'alpha'
  • Passing alpha as 50 instead of 0.5
  • Using named parameters start= and end= which are invalid
3. Given the following code, what will be the color and transparency of the highlighted date range?
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()
medium
A. A green shaded area with 30% opacity between Jan 2 and Jan 4
B. A green shaded area with 70% opacity between Jan 2 and Jan 4
C. A fully opaque green shaded area between Jan 2 and Jan 4
D. No shaded area will appear because alpha is too low

Solution

  1. Step 1: Understand alpha parameter meaning

    Alpha=0.3 means 30% opacity (or 70% transparent), so the color is faint but visible.
  2. Step 2: Confirm color and date range

    The color is green, and the highlighted range is from Jan 2 to Jan 4 as specified.
  3. Final Answer:

    A green shaded area with 30% opacity between Jan 2 and Jan 4 -> Option A
  4. Quick Check:

    alpha=0.3 means 30% opacity, color='green' [OK]
Hint: Alpha 0.3 means 30% opacity, not 70% [OK]
Common Mistakes:
  • Confusing alpha as transparency percentage
  • Thinking alpha=0.3 means 70% opacity
  • Assuming no highlight appears if alpha is low
4. Identify the error in the following code snippet that tries to highlight a date range:
import matplotlib.pyplot as plt
plt.axvspan('2023-01-01', '2023-01-05', color='blue', alpha=0.4)
plt.show()
medium
A. Dates are passed as strings; they should be converted to datetime objects.
B. The alpha value must be an integer, not a float.
C. The color parameter should be 'colour' instead of 'color'.
D. plt.show() is missing and must be added.

Solution

  1. Step 1: Check parameter types for axvspan

    plt.axvspan expects numeric or datetime values for start and end. Passing strings directly causes errors.
  2. Step 2: Correct usage for dates

    Convert strings to datetime objects using pd.Timestamp or datetime before passing.
  3. Final Answer:

    Dates are passed as strings; they should be converted to datetime objects. -> Option A
  4. Quick Check:

    axvspan needs datetime, not string dates [OK]
Hint: Convert date strings to datetime objects before axvspan [OK]
Common Mistakes:
  • Passing date strings directly without conversion
  • Misusing alpha as integer
  • Wrong color parameter spelling
5. You have a time series plot of daily sales data from '2023-01-01' to '2023-01-31'. You want to highlight weekends (Saturdays and Sundays) with a light gray transparent background. Which approach correctly applies this using matplotlib?
hard
A. Use plt.fill_between with weekend dates and color='gray', alpha=0.2.
B. Use plt.axvspan once with start='2023-01-01' and end='2023-01-31' and color='gray', alpha=0.2.
C. Plot vertical lines on weekends using plt.axvline with color='gray' and alpha=0.2.
D. Loop through dates, check if weekday is Saturday or Sunday, then use plt.axvspan for each weekend with color='gray' and alpha=0.2.

Solution

  1. Step 1: Identify weekend dates in the range

    Loop through each date, check if it is Saturday (weekday=5) or Sunday (weekday=6).
  2. Step 2: Highlight each weekend separately

    Use plt.axvspan for each weekend day or range with desired color and transparency.
  3. 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.
  4. 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 D
  5. Quick Check:

    Highlight weekends individually with axvspan [OK]
Hint: Highlight each weekend separately with axvspan in a loop [OK]
Common Mistakes:
  • 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
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard