循环中的 pandas 子图 [英] pandas subplots in a loop

查看:65
本文介绍了循环中的 pandas 子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,可以很好地在1行和6列中绘制出我的图 我尝试将其绘制为2x3或3x2失败 我在熊猫的.plot()实现中缺少什么吗?

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 ?

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

要获得2x3,我在下面做了尝试,没有太大变化.

轴具有(2,3)形状,我无法将正确的参数传递到最后一行ax = axes. 理想情况下,我应该有ax = axes [x] [y]之类的东西,其中(x,y)在[(0,0),(0,1),(0,2),(1,0),(1 ,1),(1,2)]从而具有确切的轴形状,但我只需要枚举即可获得该索引"列表...

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

推荐答案

轴是ndarray,我需要一种通过索引访问它的方法,幸运的是,

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

这篇关于循环中的 pandas 子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆