Python Forum

Full Version: Plotting A Time Series With Shaded Recession Bars
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am trying to reconstruct time series graphs from FRED through Python.

I am having trouble however finding a simple way to add shaded bars denoting start and end dates for recessions onto a basic time series plot.

I have loaded data for recession dates from FRED that looks like:
Date Recession
10/1/67 0
1/1/68 0
4/1/68 0
7/1/68 0
10/1/68 0
1/1/69 0
4/1/69 1
7/1/69 1
10/1/69 1
1/1/70 1
4/1/70 1
7/1/70 1
10/1/70 1
Perhaps an area plot or a bar plot (commented)?

from pandas import read_csv
import matplotlib.pyplot as plt
from io import StringIO

if __name__ == "__main__":
    df = read_csv(StringIO("""Date Recession tsval
10/1/1967 0 .1
1/1/1968 0 .2
4/1/1968 0 .3
7/1/1968 0 .4
10/1/1968 0 .5
1/1/1969 0 .4
4/1/1969 1 .3
7/1/1969 1 .2
10/1/1969 1 .1
1/1/1970 1 .2
4/1/1970 1 .3
7/1/1970 1 .4
10/1/1970 1 .5"""), sep=" ")
    df["nonrecession"] = 1-df.Recession
    # ax=df.plot(x="Date",y=["Recession","nonrecession"],kind="bar", stacked=True)
    ax=df.plot(x="Date",y=["Recession","nonrecession"],kind="area", stacked=True)
    df.plot(x="Date",y="tsval", ax=ax)
    plt.show()