3
votes

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() implementation of pandas ? plot 1 by 6

fig, axes = plt.subplots(nrows=1, ncols=6)
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[j])

edit : to get 2x3 I tried that below, not much of a change.

axes has a (2,3) shape and I'm unable to pass the correct parameter into the last line ax=axes. Ideally I should have something like ax = axes[x][y] where (x,y) is in [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)] thus having the exact shape of axes, but I'm just able with just enumerate to get that list of "indices"...

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[j])
3
Please edit your post and add the code where you attempted to plot 2x3/3x2.MattDMo

3 Answers

4
votes

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])
2
votes

Similarly you can also do:

for i, ax in enumerate(axes.reshape(-1)):
     df[spfvL[i]].plot(ax=ax)
0
votes

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