-1

I have a code that reads a .csv file from specified folder and it generates .png with plotted chart. How can I write loop which would read all files from folder one by one and for each plot their chart (.png) respectively.

import os
import sys
import numpy as np
import datetime
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime



# csv header
time_format = '%Y-%m-%d %H:%M:%S'
col_names = ["first_action_time","stable", "smooth", "sbase", "prebase", "leastsquares","uplift","base"]
dtypes = ["object", "uint8", "uint8", "uint8", "uint8", "uint8", "uint8", "uint8"]

# read from csv 
data = np.genfromtxt('D:\python34\\data_2016-10-09 08_26_28.csv',skip_header=1,usecols = (0,1,2,3,4,5,6,7), names=col_names, delimiter=';',  dtype=dtypes)

# x-axis datetimeformat
x = [datetime.strptime(x.decode("utf-8"), time_format) for x in data['first_action_time']]

datemin=min(x)
datemax=max(x)

#plt.title(importame)

fig = plt.figure(figsize=(40,8))
ax = plt.axes()
ax.set_xlim(datemin, datemax)

plt.plot(x,data['stable'],color='purple',label='stable')
plt.plot(x,data['smooth'],color='green',label='smooth')
plt.plot(x,data['sbase'],color='orange',label='sbase')
#plt.plot(x,data['prebase'],color='yellow',label='prebase')
#plt.plot(x,data['leastsquares'],color='red',label='leastsquares')
plt.plot(x,data['uplift'],color='blue',label='uplift',linestyle='dotted')
plt.plot(x,np.array(data['base']),color='red',label='base',linestyle='dashed')
plt.legend()
fig.autofmt_xdate()
plt.savefig('D:\python34\\test.png')
harunB10
  • 4,823
  • 15
  • 63
  • 107

1 Answers1

1

The general and most simple case would be to create the figures in a loop and save them. The only important thing to mind is that the previous figure should be closed before creating a new one.

import matplotlib.pyplot as plt
import numpy as np
import glob

#create list of files
files = glob.glob("*.csv")

#loop over list
for f in files:
    # read in data
    data = np.genfromtxt(f) 
    #close previous figure, if one exists
    plt.close()
    #create new figure and do plotting
    fig = plt.figure()
    ax = plt.subplot(111)
    ax.plot(data)
    #save figure
    plt.savefig(f[:-4]+".png")

See also

  1. https://stackoverflow.com/a/16368570/4124317
  2. Matplotlib and Pyplot.close() not releasing memory? - backend related Qt4Agg
  3. How to speed up matplotlib when plotting and saving lots of figures?

for the case that plotting is too slow or consumes too much memory.

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712