Highlighting date ranges helps you focus on important time periods in your charts. It makes trends or events easier to see.
0
0
Highlighting date ranges in Matplotlib
Introduction
You want to show a special event period on a timeline chart.
You need to emphasize weekends or holidays in a time series plot.
You want to compare data before and after a specific date range.
You want to mark a maintenance window or outage period in logs.
You want to visually separate different phases in a project timeline.
Syntax
Matplotlib
ax.axvspan(start_date, end_date, color='color', alpha=transparency)start_date and end_date are dates or numbers marking the range.
color sets the highlight color, and alpha controls transparency (0 to 1).
Examples
Highlights the date range from January 1 to January 10, 2023, with a light yellow color.
Matplotlib
ax.axvspan('2023-01-01', '2023-01-10', color='yellow', alpha=0.3)
Highlights March 15 to March 20, 2023, in semi-transparent red using pandas timestamps.
Matplotlib
ax.axvspan(pd.Timestamp('2023-03-15'), pd.Timestamp('2023-03-20'), color='red', alpha=0.5)
Sample Program
This code plots values over 30 days and highlights January 10 to January 15 with a light green shade.
Matplotlib
import matplotlib.pyplot as plt import pandas as pd # Create dates and values dates = pd.date_range('2023-01-01', periods=30) values = range(30) fig, ax = plt.subplots() ax.plot(dates, values) # Highlight a date range ax.axvspan(pd.Timestamp('2023-01-10'), pd.Timestamp('2023-01-15'), color='green', alpha=0.3) ax.set_title('Highlighting Date Range Example') ax.set_xlabel('Date') ax.set_ylabel('Value') plt.show()
OutputSuccess
Important Notes
Use axvspan to highlight vertical ranges (dates on x-axis).
Adjust alpha to make the highlight more or less visible.
Make sure your dates are in a format matplotlib understands, like pandas Timestamps.
Summary
Use axvspan to highlight date ranges on time series plots.
Set color and transparency to make highlights clear but not distracting.
Highlighting helps focus attention on important periods in your data.