简体   繁体   English

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

[英]Add a second data series to a sub-plot in Matplotlib

So I have this code which produces subplots nicely, laid out in a grid. 因此,我有这段代码,可以很好地产生子图,并以网格的形式排列。 Data is in Pandas DataFrames. 数据位于Pandas DataFrames中。

I can't figure out how to add a second data series to the subplots? 我不知道如何向子图中添加第二个数据系列? So now I plot fullyrs.Units and I want to add merged2.fcast.plot(style='r') I seem to be missing a reference to get the figure for the subplot? 所以现在我绘制了fullyrs.Units并且想添加merged2.fcast.plot(style='r')我似乎缺少获取该子图图的参考? A few things I've tried end up with plots outside the "loop". 我尝试过的一些事情最终都超出了“循环”之外的情节。

#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))

You've already created ax with plt.subplots so you just need to pass ax=ax to merged2.fcast.plot pandas call instead of setting ax=... , which creates a new axis. 您已经使用plt.subplots创建了ax ,因此您只需要将ax=ax传递给merged2.fcast.plot pandas调用即可,而无需设置ax=...来创建新轴。 eg. 例如。

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))

You probably already know this but you could also set the figure size with fig, axs = plt.subplots(nrows, 2, sharey=False, figsize=(25, 7*nrows)) instead of setting it globally in the rcparams . 您可能已经知道这一点,但是也可以使用fig, axs = plt.subplots(nrows, 2, sharey=False, figsize=(25, 7*nrows))来设置图形大小,而不是在rcparams全局设置它。 Of course, you may have other figures you want to control in the rest of your code. 当然,在其余的代码中,您可能还需要控制其他图形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM