简体   繁体   中英

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.

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? 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. 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 . Of course, you may have other figures you want to control in the rest of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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