Skip to content
Customize Time Series Plots
Customize Time Series Plots
Customizing your time series plots by highlighting important events in time is a great way to draw attention to key insights and communicate them efficiently.
# Load packages
import pandas as pd
import matplotlib.pyplot as plt
# Upload your data as CSV and load as data frame
df = pd.read_csv(
"data.csv",
parse_dates=["datestamp"], # Tell pandas which column(s) to parse as dates
index_col="datestamp", # Use a date column as your index
)
# Specify a particular subset to analyze
sub = df["2006-01-01":"2010-01-01"]
sub.head()
# See available styles plt.style.available
plt.style.use("ggplot")
ax = sub.plot(y=["Agriculture", "Finance", "Information"], figsize=(12, 7))
# Customize title and labels
ax.set_title("Unemployment rate over time")
ax.set_ylabel("Unemployment rate in %")
ax.set_xlabel("Date")
# Add a vertical red shaded region
ax.axvspan(
"2007-01-01", # From
"2008-01-12", # To
color="yellow", # Set color of region
alpha=0.3, # Set Transparency
)
# Add a vertical line
ax.axvline("2008-09-01", color="red", linestyle="--")
# Add a horizontal green shaded region
ax.axhspan(
5.5, # From
6.5, # To
color="green", # Set color of region
alpha=0.3, # Set Transparency
)
# Add a horizontal line
ax.axhline(13, color="orange", linestyle="--")
# Annotate your figure
plt.annotate(
"Healthy unemployment rate", # Annotation text
xy=("2010-01-01", 5.7), # Annotation position
xycoords="data", # The coordinate system that xy is given in
color="black", # Text Color
)
plt.annotate(
"Financial Crisis", # Annotation text
xy=("2007-04-01", 17.5), # Annotation position
xycoords="data", # The coordinate system that xy is given in
color="black", # Text Color
)
plt.show()