0

So I have this text file that i'm trying to plot. It has 5 columns of simulated data and im trying to plot each column from 2 - 5 to the 1st column.

import matplotlib.pyplot as plt
import numpy as np

with open('SampleData.txt') as f:
    data = f.read()
data = data.split('\n')

x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
ax.legend()
plt.show()

returning ValueError: could not convert string to float:

Anyway I can fix this?

Thank you

3 Answers 3

3
import matplotlib.pyplot as plt
import numpy as np

with open('SampleData.txt') as f:
    data = f.read()
data = data.split('\n')

x = [float(row.split(' ')[0]) for row in data]
y = [float(row.split(' ')[1]) for row in data]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
ax.legend()
plt.show()

It seems that it's a type coercion problem. Let me know if that helps.

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

3 Comments

Tried it, still returns a 'ValueError'.
Sorry you actually helped with my question, the actual error is now ValueError: could not convert string to float: . So i'll see what i can do with that. Thank you.
Does your data have a header? If so, eliminate it and read the rest in.
2

The type of the data you obtained from the text file is string. That is to say, before you plot it, you first need to convert it into float type. It can be easily done by float().

x = [float(row.split(' ')[0]) for row in data]
y = [float(row.split(' ')[1]) for row in data]

Make sure that the format of input data is legal for float().

For ValueError: could not convert string to float:, it depends on your text file. There may be some unformatted data in it which cannot be directly converted into float type.

Comments

0

Try typcasting your split to an integer before using the add_subplot

2 Comments

More comment than answer
Agree. I'm still trying to figure out the way this works. I thougt by hitting the up arrow on your post I was saying your answer was better. My bad.

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.