0
0
Matplotlibdata~30 mins

Highlighting date ranges in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Highlighting Date Ranges
📖 Scenario: You work as a data analyst for a company that tracks daily sales over a month. You want to visually highlight a specific date range on the sales chart to show a promotional period.
🎯 Goal: Create a line chart of daily sales and highlight the sales during the promotional date range using a shaded area.
📋 What You'll Learn
Create a dictionary called sales_data with dates as keys (strings in 'YYYY-MM-DD' format) and sales numbers as values.
Create a variable called promo_start with the start date of the promotion as a string.
Create a variable called promo_end with the end date of the promotion as a string.
Use matplotlib to plot the sales data as a line chart.
Highlight the promotional date range on the chart using ax.axvspan().
💡 Why This Matters
🌍 Real World
Highlighting date ranges on charts helps businesses see important periods like promotions, holidays, or events clearly in their data.
💼 Career
Data analysts and scientists often need to visualize time series data and emphasize specific periods to communicate insights effectively.
Progress0 / 4 steps
1
Create the sales data dictionary
Create a dictionary called sales_data with these exact entries: '2024-06-01': 150, '2024-06-02': 200, '2024-06-03': 180, '2024-06-04': 220, '2024-06-05': 210.
Matplotlib
Need a hint?

Use curly braces {} to create a dictionary. Each entry has a date string as key and an integer as value.

2
Set the promotional date range
Create two variables: promo_start set to '2024-06-02' and promo_end set to '2024-06-04'.
Matplotlib
Need a hint?

Assign the date strings directly to the variables.

3
Plot the sales data and highlight the promo range
Import matplotlib.pyplot as plt. Convert the keys of sales_data to datetime objects using pd.to_datetime from pandas. Plot the sales data as a line chart with dates on the x-axis and sales on the y-axis. Use ax.axvspan() to highlight the area between promo_start and promo_end with a light blue color and 30% transparency.
Matplotlib
Need a hint?

Use pd.to_datetime() to convert date strings. Use ax.plot() to draw the line. Use ax.axvspan() to shade the date range.

4
Display the plot
Add a line to display the plot using plt.show().
Matplotlib
Need a hint?

Use plt.show() to display the plot window.