【问题标题】:Add a second data series to a sub-plot in Matplotlib在 Matplotlib 的子图中添加第二个数据系列
【发布时间】:2014-02-02 21:34:21
【问题描述】:

所以我有这段代码可以很好地生成子图,并以网格形式布置。数据在 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))

【问题讨论】:

  • 您已经使用plt.subplots 创建了ax,所以您是否只需将ax=ax 传递给merged2.fcast.plot 而不是设置ax=...
  • @Rauparaha,没错!谢谢!如果你回答我可以标记它
  • 已完成,很高兴能够提供帮助!

标签: python matplotlib pandas


【解决方案1】:

您已经使用plt.subplots 创建了ax,因此您只需将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 中全局设置它。当然,您可能还想在其余代码中控制其他数字。

【讨论】:

  • 感谢最后的提示!还很早学习 MPL/pyplot
猜你喜欢
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多