【问题标题】:How to build subplots of pandas data frames within a loop?如何在循环中构建熊猫数据框的子图?
【发布时间】:2019-06-25 18:51:36
【问题描述】:

我想创建一个函数来创建类似变量的子数据帧(通过正则表达式)。接下来,这些子数据帧中的每一个都被绘制为图中轴上的子图。该函数输出所有子图的图形和轮廓,但不绘制数据。

我查看了网站上的几篇文章,包括“循环中的熊猫子图”和“带有 for 循环的子图”。我用类似主题搜索的问题有非常不同的问题。

def plot_macro_trend_cycle(df):
        fig = plt.figure(figsize=(12,8)) 
        for col,num in zip(df.columns,range(1,len(df.columns)+1)):

            df0 =pd.DataFrame(df.filter(regex = '{}'.format(col)), index = df.index)
            ax = fig.add_subplot(round((len(df.columns)/2)),2,num)
            ax.set_ylabel('{}'.format(col))  
            ax.set_xlabel('{}'.format(col))
            ax.set_title('{}'.format(col), pad=20)
        df0.plot(y = [df0.columns[0],df0.columns[1]], linewidth=0.5, ax=ax,legend=None)
        plt.tight_layout()
        plt.show()

这是我收到的错误图片。 enter image description here

【问题讨论】:

  • 您在 for 循环的每次迭代中定义一个新的 df0 变量,并且只在循环之后绘制最后一个 df0 数据帧。在循环内缩进 df0.plot() 行。
  • 非常感谢。我会尝试选择这个作为我正在寻找的答案。

标签: python-3.x pandas matplotlib


【解决方案1】:

您在for 循环的每次迭代中定义一个新的df0 变量,并且仅在循环之后绘制最后一个df0 数据帧。在循环内缩进 df0.plot() 行。

【讨论】:

    猜你喜欢
    • 2015-09-12
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2018-08-20
    • 2015-02-11
    相关资源
    最近更新 更多