python - displaying graph after importing txt file matplotlib -


i writing simple program output basic graph after importing text file. following error:

traceback (most recent call last):   file "c:\users\chris1\desktop\attempt2\ex1.py", line 13, in <module>     x.append(int(xandy[0])) valueerror: invalid literal int() base 10: '270.286' 

my python code looks this:

    import matplotlib.pyplot plt  x = [] y = []  readfile = open ('temp.txt', 'r')  sepfile = readfile.read().split('\n') readfile.close()  plotpair in sepfile:     xandy = plotpair.split(',')     x.append(int(xandy[0]))     y.append(int(xandy[1]))  print x print y    plt.plot(x, y)  plt.title('example 1') plt.xlabel('d') plt.ylabel('frequency')  plt.show()     

a snippet of text file looks this:

270.286,4.353,16968.982,1903.115 38.934,68.608,16909.727,1930.394     190.989,1.148,16785.367,1969.925          

the issue seems minor cannot seem resolve myself thanks

a solution

if want convert float values integers, change

x.append(int(xandy[0])) y.append(int(xandy[1])) 

to

x.append(int(float(xandy[0]))) y.append(int(float(xandy[1]))) 

enter image description here

the reason error

you error because built-in function int not accept string representation of float argument. documentation:

int(x=0)
int(x, base=10)
...
if x not number or if base given, x must string or unicode object representing integer literal in radix base. optionally, literal can preceded + or - (with no space in between) , surrounded whitespace. base-n literal consists of digits 0 n-1, z (or z) having values 10 35.

in case (x not number, string representation of float), means function not know how convert value. because base=10, argument can contain digits [0-9], i.e. not . (dot), implies string can not representation of float.


a better solution

i'd recommend numpy.loadtxt, way easier use:

x, y = np.loadtxt('temp.txt',     # load values file 'temp.txt'                   dtype=int,      # convert values integers                   delimiter=',',  # comma separated values                   unpack=true,    # unpack several variables                   usecols=(0,1))  # use columns 0 , 1 

which produces same x , y lists in code after correction.

with modification code can cut down to

import matplotlib.pyplot plt import numpy np  x, y = np.loadtxt('temp.txt', dtype=int, delimiter=',',                   unpack=true, usecols=(0,1))  plt.plot(x, y)  plt.title('example 1') plt.xlabel('d') plt.ylabel('frequency')  plt.show() 

Comments