1

So, here I'm trying to plot a graph using the coordinates that are provided in a file. I'm opening the file and setting the coordinates in an array to feed the array as in put to the graph.

Code:

import matplotlib
import matplotlib.pyplot as plt

x=[]
y=[]

readFile=open("coordinates.txt","r")
data = readFile.read().split("\n")

print(data)

for i in data:
    val = i.split(",")
    x.append(int(val[0]))
    y.append(int(val[1]))

plt.plot(x,y)
plt.show()

Output:

['3,22', '5,16', '-2,8', '10,43', '4,0', '']
Traceback (most recent call last):
  File "/home/nishantsikri/matplotlib from file.py", line 14, in <module>
    x.append(int(val[0]))
ValueError: invalid literal for int() with base 10: ''
0

2 Answers 2

1

The problem is that you have an empty line at the end of your file. One would need to check for that an not append it to the lists.

However, it seems the complete code can be condensed to

import numpy as np
import matplotlib.pyplot as plt

x,y = np.genfromtxt("coordinates.txt", unpack=True, delimiter=",")
plt.plot(x,y)
plt.show()

This would also automatically take care of the empty line.

Sign up to request clarification or add additional context in comments.

Comments

0

You have trailing spaces in your file. Use strip to remove trailing spaces.

data = readFile.read().strip().split("\n")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.