[英]multiple plots in same figure with one axis via python matplotlib
I'm trying to plot one diagram of both cyclical components(gdp and hoursworked) using HP-filters and matplotlib in python. 我正在尝试使用python中的HP过滤器和matplotlib绘制两个周期性组件(gdp和工作小时数)的图表。 Currently only getting one figure to plot and other figure is flatline(HoursWorked is flatlined) (Image below).
目前,只有一个图形可以绘制,而另一个图形是平面绘制(HoursWorked为平面绘制)(下图)。 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()
I think you would want to use a twin axes. 我想您想使用双轴。 Ie you want two axes which sit on top ofeach other and share the same x scale, but have a different y scale.
也就是说,您希望两个轴位于彼此的顶部,并且共享相同的x比例,但具有不同的y比例。 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.