I have the following minimal code where I want to make a plot by reading a data file specified by the user. In the plot, I want the x and y labels also to be specified by the user.
# ReadFileAndPlot.py
import numpy as np
import pylab as pl
# Use numpy to load the data contained in the file
datafile=raw_input('Enter data filename\n')
print 'Data filename :',datafile
x,y=map(string,raw_input('Enter x and y axis labels\n').split())
#x='Current'; y='Voltage'
data = np.loadtxt(datafile)
# plot the first column as x, and second column as y
pl.plot(data[:,0], data[:,1], 'ro')
pl.xlabel(x)
pl.ylabel(y)
pl.xlim(0.0, 10.)
pl.show()
However, strings are not recognized while feeding them as multiple inputs using split
. So I get the message : NameError: name 'string' is not defined
[works with int
variables though].
Any way to correct this using split
or something similar?
You don't need to use map. Simply split and assign tuple to x and y. But it will not ensure that user has given valid input (mean two words). If there will be more than two words it will break.
while True:
try:
x, y = raw_input('Enter x and y axis labels\n').split()
break
except ValueError:
print('Invalid input.')