我正在编写一个使用 matplotlib 绘制数据的代码。数据来自数千个文本文件。我能够编写可以绘制数据的循环。现在,我想为每个图添加一个标签,其中包含另一个文件中的一条信息,我已将其放入列表中:
import os
import matplotlib.pylab as plt
import numpy as np
from datetime import datetime, timedelta
time = []
t1 = []
t2 = []
t3 = []
t4 = []
t5 = []
t6 = []
newdate = []
temps = open('/Users/datafile_with_temperatures.txt','r')
sepfile = temps.read().replace('\n','').split('\r')
temps.close()
for plotpair in sepfile:
data = plotpair.split('\t')
time.append(float(data[0]))
t1.append(float(data[1]))
t2.append(float(data[2]))
t3.append(float(data[3]))
t4.append(float(data[4]))
t5.append(float(data[5]))
t6.append(float(data[6]))
for datapoint in t2,t3,t4,t5,t6:
temperatures = np.array([t2,t3,t4,t5,t6]).mean(0).tolist()
os.chdir('/Users/datafile')
path = os.listdir('/Users/datafiles')
for file in path and temperature_point in temperatures:
MtoC = []
Pressure = []
readfile = open(file,'r')
datalines = readfile.read().split("\n")
useful_data = []
for line in datalines:
line = ''.join([x for x in line if x not in [",", "\r"]])
data = [float(item) for item in line.split()]
useful_data.append(data)
combined_data = [MtoC.extend(sub_list) for sub_list in useful_data]
Mass_to_charge = MtoC[::2]
Pressure = MtoC[1::2]
plt.plot(Mass_to_charge,Pressure)
plt.title(file)
plt.text(60, 1e-07, temperature_point)
plt.xlabel('Mass to Charge Ratio')
plt.ylabel('Pressure (torr)')
plt.yscale('log')
plt.ylim([1e-10,1e-05])
plt.savefig(file+'.jpg')
plt.close()
我希望列表中的温度点列在绘图上。温度点的数量与绘图文本文件的数量相同。有数千个文本文件,其中包含用于绘制绘图的数据。每个文件相隔几秒钟,因为时间不是图中的变量。有一个文本文件,其中每个数据文件对应数千次,并具有该特定时间的温度。我想运行循环,以便它将绘制第一个数据文件,并将第一个温度点作为文本添加到绘图上,然后循环遍历每个文件并执行相同的操作。
最佳答案
Blockquote
from itertools import izip
for d2,d3,d4,d5,d6 in izip(t2,t3,t4,t5,t6):
...
izip()
类似于 zip()
但生成一个迭代器,而 zip()
一次解析它的所有输入并传递一个将单个巨大对象添加到循环中,这可能会导致较大数据集出现问题,并且速度较慢。
根据@cyber的评论进行编辑:这只适用于Python 2.x。在 Python 3.x 中,内置的 zip()
的作用与 izip()
在这里的作用相同。
关于python - 如何同时运行 2 个列表的循环,以便循环中的每个项目都匹配? [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27066323/