Save Pandas plots created in a loop into different files

时间:2018-02-01 18:41:38

标签: python pandas matplotlib jupyter-notebook

I wrote a script to graph some columns of a pandas.DataFrame. It is:

import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv('alcohol_cons_18', sep=',') #this is the loaded data
a_list=list(df.columns.values) #a list of its columns
for ielement in range(len(a_list)): #iterate over columns and make charts
    print ("column name is %s" %(a_list[ielement]))
    if a_list[ielement]!= 'age':
        df.plot(x='age', y=a_list[ielement])
        plt.savefig(a_list[ielement] + '.png') #savefigures

but the script saves figures in a cummulative way. So in the second figure there are the first and second graph, and so on.. Any idea how to modify the script to save those graphs in different files?

2 个答案:

答案 0 :(得分:2)

使用

plt.close()

记录在案here解决了您的问题?

否则,您可以尝试将绘图分配给枚举的数字,如此

for ielement in range(len(a_list)): #iterate over columns and make charts
    print ("column name is %s" %(a_list[ielement]))
    if a_list[ielement]!= 'age':
        fig = plt.figure(ielement)
        df.plot(x='age', y=a_list[ielement])
        plt.savefig(a_list[ielement] + '.png')

答案 1 :(得分:1)

plt.clf()plt.cla()取决于您是否要保存某些图形部分会清除画布。

相关问题