EngGu
EngGu

Reputation: 489

Plots in a loop are overwritten

I am trying to create several plots in a loop. The plots I create gets saved automatically in a different folder each time. This is the code

x = [2,4,6]
y = [1,2,3]
for i in x:
    for j in y:
        outputpath = './home/' + 'folder'+ str(i) + str(j)
        if not path.exists(outputpath):
            try:
                os.makedirs(outputpath)
            except OSError:
                print("Creation failed")
            else:
                print("Successfully created")
        a =  np.random.rand(1000)
        b = np.random.rand(20000)
        
        #Plotting a
        plt.scatter((range(0,len(a))),a)
        path1 = outputpath + '/' + 'a' + '.png'
        plt.savefig(path1)

        #Plotting b
        plt.scatter((range(0,len(b))),b)
        path2 = outputpath + '/' + 'b' + '.png'
        plt.savefig(path2)

The plots get saved in the appropriate folders. But every new plot that is generated is overwritten on the old plot. As shown in the figure below. This figure was created for i = 2 and j= 2. This figure is saved in ./home/folder22 and it has been overwritten with the plots generated in the previous folders as well. How do I avoid this?

enter image description here

Update: I believe I have to use plt.figure() each time before plotting?

Upvotes: 3

Views: 6339

Answers (1)

I'mahdi
I'mahdi

Reputation: 24049

you use plt.close() like below:

x = [2,4,6]
y = [1,2,3]
for i in x:
    for j in y:
        outputpath = './home/' + 'folder'+ str(i) + str(j)
        if not path.exists(outputpath):
            try:
                os.makedirs(outputpath)
            except OSError:
                print("Creation failed")
            else:
                print("Successfully created")
        a =  np.random.rand(1000)
        b = np.random.rand(20000)
        
        #Plotting a
        plt.scatter((range(0,len(a))),a)
        path1 = outputpath + './' + 'a' + '.png'
        plt.savefig(path1)
        plt.close()


        #Plotting b
        plt.scatter((range(0,len(b))),b)
        path2 = outputpath + './' + 'b' + '.png'
        plt.savefig(path2)
        plt.close()

Upvotes: 3

Related Questions