iron2man
iron2man

Reputation: 1827

Python - Plotting text file returns 'ValueError: invalid literal for float():'

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

Upvotes: 0

Views: 471

Answers (3)

Jiayi Chen
Jiayi Chen

Reputation: 44

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.

Upvotes: 2

Dunnage
Dunnage

Reputation: 99

Try typcasting your split to an integer before using the add_subplot

Upvotes: 0

hd1
hd1

Reputation: 34667

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.

Upvotes: 3

Related Questions