user7437554
user7437554

Reputation:

Save Pandas plots created in a loop into different files

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?

Upvotes: 0

Views: 1248

Answers (2)

Metropolis
Metropolis

Reputation: 2128

Does using

plt.close()

as documented here resolve your issue?

Otherwise, you can try assigning the plot to an enumerated figure, like so

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

Upvotes: 1

Ben Usman
Ben Usman

Reputation: 8387

Either plt.clf() or plt.cla() depending on whether you want to save certain figure parts would clear the canvas.

Upvotes: 0

Related Questions