我正在使用Python 2.7并导入库numpy和matplotlib。我想读取制表符分隔文本文件的多个文件名(时间,电压和压力测量值),然后在每个文件名后用%pylab显示相应的图形。
我的代码可以显示我想要的图形,但只有在我输入特定的字符串('exit')才能退出while循环。我希望在输入文件名后立即显示每个图形,并在屏幕上同时显示多个图形。我的代码下面有什么问题?
import numpy as np
import matplotlib.pylab as plt
filename = ''
filepath = 'C:/Users/David/My Documents/Cardiorespiratory Experiment/'
FileNotFoundError = 2
while filename != 'exit':
is_valid = False
while not is_valid :
try :
filename = raw_input('File name:')
if filename == 'exit':
break
fullfilename = filepath+filename+str('.txt')
data = np.loadtxt(fullfilename, skiprows=7, usecols=(0,1,2))
is_valid = True
except (FileNotFoundError, IOError):
print ("File not found")
t = [row[0] for row in data]
v = [row[1] for row in data]
p = [row[2] for row in data]
#c = [row[3] for row in data]
plt.figure()
plt.subplot(2, 1, 1)
plt.title('Graph Title ('+filename+')')
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.plot(t, v, color='red')
plt.subplot(2, 1, 2)
plt.xlabel('time (s)')
plt.ylabel('pressure (kPa)')
plt.plot(t, p, color='blue')
plt.show()
我已经尝试过Padraic Cunningham的建议,只使用一个while循环来获取文件名,这是一个改进。但是当我将图形命令放在循环中时,该图形显示为一个空窗口,其中显示消息“Not Responding”。只有在退出while循环后,图形才会出现在图中。我希望在获取文件名后立即显示数字。这是我目前的代码:
import numpy as np
import matplotlib.pylab as plt
filename = ''
filepath = 'C:/Users/David/My Documents/Cardiorespiratory Experiment/'
FileNotFoundError = 2
Count = 0
while Count <= 4:
try :
filename = raw_input('File name:')
fullfilename = "{}{}.txt".format(filepath, filename)
data = np.loadtxt(fullfilename, skiprows=7, usecols=(0,1,2))
is_valid = True
except (FileNotFoundError, IOError):
print ("File not found")
Count += 1
t = [row[0] for row in data]
v = [row[1] for row in data]
p = [row[2] for row in data]
plt.figure()
plt.subplot(2, 1, 1)
plt.title('Graph Title ('+filename+')')
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.plot(t, v, color='red')
plt.subplot(2, 1, 2)
plt.xlabel('time (s)')
plt.ylabel('pressure (kPa)')
plt.plot(t, p, color='blue')
plt.show()
答案 0 :(得分:0)
只需使用一个循环即可获取文件名:
while True:
try :
filename = raw_input('File name:')
full_filename = "{}{}.txt".format(filepath, filename)
data = np.loadtxt(full_filename, skiprows=7, usecols=(0,1,2))
break # if no error break out of loop
except (FileNotFoundError, IOError): # else catch error and ask again
print ("File not found")
".txt"
已经是一个字符串,因此无需强制转换
答案 1 :(得分:0)
您应该在第二个脚本中将plt.show()
替换为plt.pause(1)
。看看this类似问题的答案。