将第二个数据系列添加到Matplotlib中的子图

时间:2014-02-02 21:34:21

标签: python matplotlib pandas

所以我有这个代码很好地生成子图,在网格中布局。数据在Pandas DataFrames中。

我无法弄清楚如何在子图中添加第二个数据系列? 所以现在我绘制fullyrs.Units并且我想添加merged2.fcast.plot(style='r')我似乎缺少一个参考来获得子图的数字?我试过的一些事情最终会出现在"循环之外的情节"。

#area_tabs=list(map(str, range(1, 28)))
area_tabs=['1','2','3']
nrows = int(math.ceil(len(area_tabs) / 2.))
figlen=nrows*7 #adjust the figure size height to be sized to the number of rows
plt.rcParams['figure.figsize'] = 25,figlen 
fig, axs = plt.subplots(nrows, 2, sharey=False)
for ax, area_tabs in zip(axs.flat, area_tabs):  
    fullyrs,lastq,fcast_yr,projections,yrahead,aname,actdf,merged2,mergederrs,montdist,ols_test, mergedfcst=do_projections(actdf,aname)
#    ax=merged2.fcast.plot(style='r') <<<< I want to get this to plot in the same sub-plot as below
    fullyrs.Units.plot(ax=ax, title='Area: {0} Forecast for 2014 {1} vs. Actual 2013 of {2} '.format(unicode(aname),unicode(merged2['fcast'][-1:].values), lastyrtot))

1 个答案:

答案 0 :(得分:1)

您已使用ax创建plt.subplots,因此您只需将ax=ax传递给merged2.fcast.plot pandas,而不是设置ax=...,这会创建一个新轴。例如

for ax, area_tabs in zip(axs.flat, area_tabs):  
    fullyrs,lastq,fcast_yr,projections,yrahead,aname,actdf,merged2,mergederrs,montdist,ols_test, mergedfcst=do_projections(actdf,aname)
    merged2.fcast.plot(ax=ax, style='r') <<<< I want to get this to plot in the same sub-plot as below
    fullyrs.Units.plot(ax=ax, title='Area: {0} Forecast for 2014 {1} vs. Actual 2013 of {2} '.format(unicode(aname),unicode(merged2['fcast'][-1:].values), lastyrtot))

您可能已经知道这一点,但您也可以使用fig, axs = plt.subplots(nrows, 2, sharey=False, figsize=(25, 7*nrows))设置数字大小,而不是在rcparams中全局设置。当然,您可能还需要在其余代码中控制其他数据。