how to color different times in matplotlib based on a classification condition, like when there was a recssion in python

You can use matplotlib's fill_between function to shade specific regions of the plot based on a condition. Here's an example of how to shade the regions where the GDP growth rate was negative (i.e. during a recession) in a time series plot:

main.py
import matplotlib.pyplot as plt
import pandas as pd

# Load some example GDP data
df = pd.read_csv('gdp_data.csv', index_col='date')

# Define a function to check if the GDP growth rate is negative
def is_recession(gdp_growth_rate):
    return gdp_growth_rate < 0

# Calculate the GDP growth rate
df['gdp_growth_rate'] = df['gdp'].pct_change() * 100

# Create a boolean Series indicating whether each point is in a recession or not
in_recession = df['gdp_growth_rate'].apply(is_recession)

# Create the plot
fig, ax = plt.subplots()
ax.plot(df.index, df['gdp'])

# Shade the regions where we were in a recession
ax.fill_between(df.index, 0, df['gdp'], where=in_recession, color='red', alpha=0.3)

# Add labels and title
ax.set_xlabel('Year')
ax.set_ylabel('GDP (trillions of dollars)')
ax.set_title('US GDP over time with recessions shaded')

plt.show()
854 chars
30 lines

This code loads some example GDP data (stored in a CSV file), calculates the growth rate of the GDP, and then creates a boolean Series that indicates whether each point is in a recession or not (using the is_recession function). It then creates a standard time series plot of the GDP, and uses fill_between to shade the regions where we were in a recession (specified by the in_recession boolean Series).

You can customize the color and opacity of the shading by changing the color and alpha arguments in the fill_between function.

gistlibby LogSnag