I am trying to reconstruct a time series graphs from FRED: https://fred.stlouisfed.org/series/LABSHPUSA156NRUG using Python. However, I am unable to get a clean figure where the time series is overlaid with the area graph representing the recession bars.

I am quite new to python so it's been frustrating to find a simple reason why my attempts are not working.

I have attempted this two ways.

My first attempt looks like this:

fig, ax = plt.subplots()
ls_data.plot.line(ax=ax, figsize=(8,5), x='Date', color=blue)
rec_data.plot.area(ax=ax, figsize=(8,5), x='Date', alpha=0.5, color=gray)

And produces the following perplexing mess: enter image description here

My second attempt goes for the "ax2 = ax1.twinx()" route

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

ls_data.plot.line(figsize=(8,5), x='Date', color=blue)
rec_data.plot.area(figsize=(8,5), x='Date', alpha=0.5, color=gray)

However this produces two separate figures instead.

enter image description here

enter image description here

One possible issue is that the x-values for the labor share are plotted in individual years whereas the x-values for recession are plotted in months. But based on the second attempt, it looks like the graphs should overlay smoothly but then I'm liable to get the same result as in my first attempt. Would transforming the recession data provide a fix?

Edit: The data for recession dates are available here. https://fred.stlouisfed.org/series/USREC#:~:text=For%20daily%20data%2C%20the%20recession,the%20month%20of%20the%20trough.

  • $\begingroup$ Can you share the input data for the recession periods? $\endgroup$
    – Oxbowerce
    Jan 28 at 11:15
  • $\begingroup$ Thanks for commenting. The recession data are given in binary terms where months in recession are given a value of 1 and a value of 0 otherwise. You can download the data set here: fred.stlouisfed.org/series/…. $\endgroup$ Jan 29 at 3:20

Using the data from FRED for both labour data and recession data and slight adjustments to your code I think I get the result you want:

import pandas as pd
import matplotlib.pyplot as plt

# read in data
rec_data = pd.read_csv("USREC.csv")
ls_data = pd.read_csv("LABSHPUSA156NRUG.csv")

# make sure date columns are actual dates
rec_data["DATE"] = pd.to_datetime(rec_data["DATE"])
ls_data["DATE"] = pd.to_datetime(ls_data["DATE"])

# create plot
fig, ax = plt.subplots()
ls_data.plot.line(ax=ax, figsize=(8, 5), x='DATE', color="blue")
rec_data.plot.area(ax=ax, figsize=(8, 5), x='DATE', alpha=0.5, color="gray")
plt.xlim("1950-01-01", "2020-01-01")
plt.ylim(0.58, 0.65)

enter image description here

  • $\begingroup$ By god, you're a hero. Thank you. $\endgroup$ Jan 29 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.