1

I'm trying to plot one diagram of both cyclical components(gdp and hoursworked) using HP-filters and matplotlib in python. Currently only getting one figure to plot and other figure is flatline(HoursWorked is flatlined) (Image below). Any pointers on how to improve code.

import statsmodels.api as sm
import matplotlib.pyplot as plt
pandas_datareader import data
import datetime as dt

start, end = dt.datetime(1965, 1, 1), dt.datetime(2016,12, 31)

gdp = data.DataReader('GDPC1', 'fred', start, end)
HoursWorked = data.DataReader('PRSCQ', 'fred', start, end)

plt.figure(1)
plt.subplot(211)
plt.plot(gdp)

plt.title('RealGDP and Hours Worked')
cycle, trend = sm.tsa.filters.hpfilter(gdp, 1600)

plt.figure(1)
plt.subplot(211)
plt.plot(HoursWorked)
ax = plt.gca()
ax.set_xticklabels([])

plt.show()

enter image description here [enter image description here2

5
  • prscq is not defined in this code snippet. Commented Apr 3, 2017 at 7:46
  • @Crispin typo, it's hours worked. Commented Apr 3, 2017 at 7:57
  • What does HoursWorked look like? It could be that your y axis has scaled in order to encompass all the data for gdp and therefore HoursWorked just looks like a flat line. You could try just plotting HoursWorked on its own to see? Commented Apr 3, 2017 at 8:08
  • @davidG attached an image for HoursWorked. That could very much be the reason. However I need them on one graph to view trend, is it possible to scale up to accommodate data points. Im fairly new to matplotlib and python as a whole Commented Apr 3, 2017 at 8:28
  • @pyt the answer below will do the trick Commented Apr 3, 2017 at 11:17

1 Answer 1

2

I think you would want to use a twin axes. I.e. you want two axes which sit on top ofeach other and share the same x scale, but have a different y scale. This can be done with the following code:

import matplotlib.pyplot as plt
import pandas_datareader.data 
import datetime as dt

start, end = dt.datetime(1965, 1, 1), dt.datetime(2016,12, 31)

gdp = pandas_datareader.data.DataReader('GDPC1', 'fred', start, end)
HoursWorked = pandas_datareader.data.DataReader('PRSCQ', 'fred', start, end)

fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.plot(gdp, label="GDP")
ax2.plot(HoursWorked, color="C2", label="HoursWorked")

ax.set_title('RealGDP and Hours Worked')

ax.legend(loc=2)
ax2.legend(loc=4)
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Any chance you also know how to have only one caption?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.