Matplotlib: Saved files in a loop are not the same as in show ()

My program shows the correct graph in plt.show(), but not in fig.savefig. I am new to python, so sorry if this is something simple. I am using python 2.7.10, windows (10).

import numpy as np
import matplotlib.pyplot as plt

data = np.genfromtxt('strike_details.txt')  #, skip_header= 0
header= 3
information=10000
width = 5
files = 16
types = 4

length = information + header
frames = data[header:length,0]

fig= plt.figure()
plt.grid(True)

for i in range(0,int(files)):
    density=data[(header+i*length):(length+i*length),4]
    plt.plot(frames,density, label=data[i*length+1][2])

    for j in range (0,files/types):
        if i==(types*(j+1)-1):  
            plt.legend(loc='best')
            plt.xlabel('$Frames$', fontsize=22)
            plt.ylabel('$Density$', fontsize=22)
            fig.savefig(str(data[j*length+1][0])+'_'+str(data[j*length+1][1])+'_'+str(data[j*length+1][2])+'.png',format='png', dpi=fig.dpi)        
            plt.show()
            plt.clf()

The program creates four files with different file names, but all of them are the first group that you see in plt.show.

If I missed anything important, let me know.

Thanks,

Lio

+4
source share
1 answer

, API- matplotlib. plt.show(), fig , . :

import matplotlib.pyplot as plt

fig = plt.figure()

for n in range(0,10):
    plt.plot(list(range(0,n)))
    fig.savefig('test%d.png' % n)
    plt.show() 
    plt.clf()

show(), .

- plt.gcf():

plt.gcf().savefig(...)

:

for i in range(0,int(files)):
    fig= plt.figure()
    plt.grid(True)
    ...
+3

Source: https://habr.com/ru/post/1623310/


All Articles