I have a data file where I want to plot specific lines of the second column. My script is as follows:
f=open('datafile','r')
lines1=f.readlines()[4:24]#since I want the values from the 4th to the 23rd line
lines2=f.readlines()[33:54]#I want the values from the 33rd to the 53rd line
f.close()
x1=[]
y1=[]
for line in lines1:
p=line.split()
x1.append(float(p[1]))#the values are in the second column
for line in line2:
p=line.split()
y1.append(float(p[1]))
xv=np.array(x1)
yv=np.array(y1)
plt.plot(xv,yv)
However, at the end I have an error saying “x and y must have same first dimension”. I am not very experienced with python, could somebody advise me any alternative or let me know what am I doing wrong? How could I extract only those rows with a different way?
I want to plot x= column 2 from row 4 to row 25 against y=column 2 from row 33 to row 54.
Thank you very much in advance.
Regards,
Gio
What you are doing wrong is calling
readlinestwo times.A file object behaves like an iterator. Calling
readlineswill exhaust it. The second call will return an empty list.You can get the list of lines once and then work with it:
Still, it looks like the lengths of the lists will differ by 1, I guess you need to correct that.
Also note that you don’t need to convert lists to
numpyarrays to plot them.