Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

python - pandas subplots in a loop

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])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...