我是Python的新手
尝试绘制来自多个类似文件的一列数据(见下文)
#0 Date-time: 20/02/2015 22:50
#1 Recorder: 35X1078
#2 File type: 0
#3 Columns: 7
#4 Channels: 4
#5 Field separation: 1
#6 Decimal point: 1
#7 Date def.: 0 2
#8 Time def.: 0
#9 Channel 1: Temperature(°C) Temp(°C) 3 1
#10 Channel 2: Depth(m) Depth(m) 2 2
#11 Reconvertion: 0
#14 Channel 3: Pitch(°) Pitch(°) 1 1
#18 Channel 4: Roll(°) Roll(°) 1 1
#19 Line color: 1 2 3 4
1 20-02-15 12:00:00 8.615 -2.64 92.3 88.8
2 20-02-15 12:00:01 8.615 -2.64 92.1 89.1
3 20-02-15 12:00:02 8.615 -2.64 92.1 87.2
4 20-02-15 12:00:03 8.615 -2.64 92.6 89.6
5 20-02-15 12:00:04 8.615 -2.64 91.9 91.5
6 20-02-15 12:00:05 8.615 -2.64 91.9 88.7
7 20-02-15 12:00:06 8.615 -2.64 92.1 89.7
8 20-02-15 12:00:07 8.615 -2.64 92.5 87.2
9 20-02-15 12:00:08 8.615 -2.66 92.1 87.6
10 20-02-15 12:00:09 8.615 -2.64 92.9 87.4
数据有多个要忽略的标题行,忽略第一列
我绘制单个文件的代码是:
import matplotlib.pyplot as plt
import pandas as pd
import sys
print 'loading & plotting: '+sys.argv[1]+'.txt'
data=pd.read_csv(sys.argv[1]+'.txt',delimiter='\s',skiprows=17,names=['index','date','time','temp','pressure','pitch','roll'],infer_datetime_format=True)
fig,axes = plt.subplots(4,1)
data.plot('time','temp',ax=axes[0])
axes[0].set_ylabel('temperature $^\circ$C')
data.plot('time','pressure',ax=axes[1])
axes[1].set_ylabel('pressure (Bar)')
data.plot('time','pitch',ax=axes[2])
axes[2].set_ylabel('pitch $^\circ$')
data.plot('time','roll',ax=axes[3])
axes[3].set_ylabel('roll $^\circ$')
fig.suptitle('Data from Star Oddi pitch + roll sensor X1078: %s'%(data['date'][0]))
fig.savefig('X1078_uimage.png',bbox_inches='tight')
plt.show()
我知道我的图表布局是垃圾,我可以自己整理,但我现在想要将多个文件绘制到相同的图表上。
答案 0 :(得分:1)
您只需要在更改数据时在循环内重复绘图调用,但不要创建数字并将其保存在循环之外。
如果你经常处理文件列表,那么glob模块很好用。
from glob import glob
import matplotlib.pyplot as plt
files = glob("*.txt")
fig, ax = plt.subplots()
for f in files:
print("Current file is"+f)
#your csv loading into data
data.plot('time','temp',ax=axes[0])
#outside of the for loop
plt.savefig("myplots.png")