pandas subplots in a loop

前端 未结 3 486
后悔当初
后悔当初 2020-12-21 06:10

I have this code which plots well my plots in a 1 row and 6 columns I tried unsuccessfully to plot it in a 2x3 or 3x2 Is there something I\'m missing in the .plot() implemen

相关标签:
3条回答
  • 2020-12-21 06:55

    Similarly you can also do:

    for i, ax in enumerate(axes.reshape(-1)):
         df[spfvL[i]].plot(ax=ax)
    
    0 讨论(0)
  • 2020-12-21 07:02

    Alternatively you can add subplots inside the loop :

    fig = plt.figure(figsize=(15, 10))
    for j, i in enumerate(spfvL):
        fig.add_subplot(2, 3, i+1)
        df.loc[:, ['pred' + str(i), 'spfv' + str(i)]].plot(ax=axes.flat[j])
    
    0 讨论(0)
  • 2020-12-21 07:04

    axes being a ndarray I needed a way to access it by index, and fortunately the flat method does just that.

    fig, axes = plt.subplots(nrows=2, ncols=3)
    spfvL = [6, 11, 22, 33, 44, 55]
    for j, i in enumerate(spfvL):
        df['spfv' + str(i)] = pd.rolling_std(df['r VIX'], i) * np.sqrt(252)
        res = smf.ols(formula='spfv'+ str(i)+' ~ Q(\'VIX Index\')', data=df).fit()
        df['pred'+ str(i)] = better_predict(res, df)
        df.loc[:, ['pred' + str(i), 'spfv' + str(i)]].plot(ax=axes.flat[j])
    
    0 讨论(0)
提交回复
热议问题