I am using Python 2.7 and importing libraries numpy and matplotlib. I want to read multiple file names of tab-delimited text files (time, voltage and pressure measurements) and after each one display the corresponding graph with %pylab.
My code can display the graph I want, but only after I enter the specific string ('exit') to get out of the while loop. I want to see each graph displayed immediately after the file name has been entered and have multiple figures on the screen at once. What's wrong with my code below?
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()
I have tried Padraic Cunningham's suggestion to use only a single while loop to get the file name and that's an improvement. But when I put the graphing commands inside the loop, the figure comes up as an empty window with the message "Not Responding". The graph appears in the figure only after exiting the while loop. I want the figures to appear immediately upon getting the file name. Here's my current code:
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()