【问题标题】:Plot multiple csv files with Python/matplotlib loop使用 Python/matplotlib 循环绘制多个 csv 文件
【发布时间】:2015-07-30 18:21:12
【问题描述】:

我有一个包含多个 .csv 文件的目录,每个文件只有两列(日期和整数)。 我试图让这段代码循环遍历每个文件并单独绘制它们,以便每个 .csv 都有一个对应的 .png。每次运行时,我都会得到正确数量的 .png 文件,但每个文件都有完全相同的数据。我已经实现了plt.clf() 方法来为每个循环清除它,但它不起作用。代码如下:

import numpy as np
import pylab as pl
import matplotlib.pyplot as plt
import datetime as DT
import matplotlib.dates as mdates
import scipy
import os
import glob

rootdir='/path/to/file'

for infile in glob.glob( os.rootdir.join(rootdir, '*.csv.out') ):
    output = infile + '.out'

data= np.loadtxt(infile, delimiter=',',
         dtype={'names': ('date', 'session'),'formats': ('S10', 'i4')} )

#Organizes 2-column spreadsheet
dates, sessions = map(list, zip(*data))
print dates, sessions

x = [DT.datetime.strptime(date,"%m-%d-%y") for date in dates]
y = [sessions]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.xaxis_date()
ax.grid()
#Fills space under plotted line
ax.fill_between(x, sessions, color='blue')

# slants the x axis
fig.autofmt_xdate()
plt.plot(x,sessions)
plt.xlabel('Date')
plt.ylabel('Sessions')
plt.title('Peak Usage')

fileNameTemplate = r'\path\to\file\Plot{}.png'

for subdir,dirs,files in os.walk(rootdir):
    for count, file in enumerate(files):
        pl.savefig(fileNameTemplate.format(count), format='png')
        pl.clf() 

我根据this answer 中的解决方案对枚举器进行了建模,但我仍然遇到问题。

【问题讨论】:

    标签: python loops csv matplotlib


    【解决方案1】:

    你需要:

    • 为您的绘图定义一个函数
    • 从循环中调用该函数
    • 在所述函数的末尾包含 plt.close()。

    现在,您不会在浏览目录时创建新地块。 plot 命令需要在循环内。

    def plot():
       #do your plotting in here. If this is being called from a loop and the 
       #variables used herein are defined before, it will use the 
       #global values as they exist at the time. You can also end this function with
      fig.savefig(**args)
      plt.close()
    
    
    
    for count, file in enumerate(files):
        plot()        
    

    【讨论】:

    • 所以该函数将包含所有plot. 部分,对吗?或者它是否也将data 作为变量或参数?
    猜你喜欢
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 2015-02-07
    相关资源
    最近更新 更多