我正在尝试将pandas.dataframe.plot创建的多个图保存为gif格式。我正在使用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的单个值时,我得到了正确的图。
我想要的情节是这些我得到的情节是这些
答案 0 :(得分:0)
清除每次迭代中的图
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))
答案 1 :(得分:0)
您的问题可能会在注释中得到回答(请参见重复问题的链接),这是对代码的一些小改进:
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()