Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 251
EngGu Avatar asked Dec 21 '25 10:12

EngGu


1 Answers

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

like image 161
I'mahdi Avatar answered Dec 22 '25 23:12

I'mahdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!