如何使用Python和Matplotlib导入和绘制文件夹中的每个文件

时间:2016-12-16 17:09:30

标签: python matplotlib

我有一个代码从指定的文件夹中读取.csv文件,它生成.png并绘制图表。如何编写循环,逐个读取文件夹中的所有文件,并分别绘制每个图表(.png)。

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

1 个答案:

答案 0 :(得分:1)

一般而且最简单的情况是在循环中创建数字并保存它们。唯一重要的是要在创建新图之前关闭上一个图。

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

另见

  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?
  4. 对于绘图太慢或消耗太多内存的情况。