Python 熊猫:无法使用for循环保存多个绘图

Python 熊猫:无法使用for循环保存多个绘图,python,pandas,matplotlib,Python,Pandas,Matplotlib,我正在尝试以gif格式保存pandas.dataframe.plot创建的多个绘图。我使用for循环来迭代绘图。问题是执行循环后保存的绘图不正确。这是密码 for i in range(len(plot_cols)): grouped = cust_data[plot_cols[i]].groupby(cust_data['Cluster_ID']) mean_trans = grouped.mean() plot = mean_trans.plot(kind = 'ba

我正在尝试以gif格式保存pandas.dataframe.plot创建的多个绘图。我使用for循环来迭代绘图。问题是执行循环后保存的绘图不正确。这是密码

for i in range(len(plot_cols)):
    grouped = cust_data[plot_cols[i]].groupby(cust_data['Cluster_ID'])
    mean_trans = grouped.mean()
    plot = mean_trans.plot(kind = 'bar', figsize = [10, 7])
    plot.set_ylabel(plot_cols[i])
    fig = plot.get_figure()
    fig.savefig("C:\\Users\\utkarsh.a.ranjan\\Documents\\pyqt_data\\view_bar_graphs\\cluster_" + str(i))
当我删除for循环并替换I的各个值时,我得到了正确的绘图

我想要的是这些

取而代之的是这些情节
清除每次迭代中的绘图

for i in range(len(plot_cols)):
    grouped = cust_data[plot_cols[i]].groupby(cust_data['Cluster_ID'])
    mean_trans = grouped.mean()
    plot = mean_trans.plot(kind = 'bar', figsize = [10, 7])
    plot.set_ylabel(plot_cols[i])
    fig = plot.get_figure()
    ## Clear plot here
    plot.clf()

    fig.savefig("C:\\Users\\utkarsh.a.ranjan\\Documents\\pyqt_data\\view_bar_graphs\\cluster_" + str(i))

您的问题可能在注释中得到了回答(请参阅重复问题的链接),下面是对代码的一些小改进:

import os
def filename(string):
    return os.path.join('C:\\Users\\utkarsh.a.ranjan\\Documents\\'
                        'pyqt_data\\view_bar_graphs',
                        'cluster{}'.format(string))

for i, column in enumerate(plot_cols): 
    mean_trans = (cust_data[column]
                  .groupby(cust_data['Cluster_ID'])
                  .mean())
    ax = mean_trans.plot(kind = 'bar', figsize = [10, 7])
    ax.set_ylabel(plot_cols[i])
    fig = ax.get_figure()        
    fig.savefig(filename(i))
    # initial problem
    ax.clf()

您好,欢迎加入,请共享一个。您可以尝试将
plt.figure()
放在新画布循环的开始处。为什么在保存之前要清除?信息已保存在fig变量中,绘图信息已清除,而非fig