Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After conversion to float, matplotlib outputs cannot convert string to float

I have a program that inputs 2 txt files.

deaths.txt

29.0
122.0
453.0

years.txt

1995
1996
1997

I make lists from the data

deaths = open("deaths.txt").read().splitlines()
years = open("years.txt").read().splitlines()

then I convert the lists to int and floats

for x in years[:-1]:
    x = int(x)

for x in deaths[:-1]:
    x = float(x)

and then the part where it gives the error: ValueError: could not convert string to float

plt.plot(years, deaths)

So it says it cannot convert strings to floats. But I thought I allready did that. What could be the reason?

like image 596
Tristan Avatar asked May 18 '26 01:05

Tristan


1 Answers

The following should get you going. Rather than using readlines() to read the whole file, a better approach would be to convert each row as it is read in.

As your two data files have a different number of elements, the code makes use of zip_longest to fill in any missing death data with 0.0:

from itertools import zip_longest
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

with open('deaths.txt') as f_deaths:
    deaths = [float(row) for row in f_deaths]

with open('years.txt') as f_years:
    years = [int(row) for row in f_years]

# Add these to deal with missing data in your files, (see Q before edit)    
years_deaths = list(zip_longest(years, deaths, fillvalue=0.0))
years = [y for y, d in years_deaths]
deaths = [d for y, d in years_deaths]

print(deaths)
print(years)

plt.xlabel('Year')
plt.ylabel('Deaths')

ax = plt.gca()
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))
ax.set_xticks(years)

plt.plot(years, deaths)
plt.show()

This will display the following on the screen, showing that the conversions to ints and floats were correct:

[29.0, 122.0, 453.0, 0.0]
[1995, 1996, 1997, 1998]    

And the following graph will then be displayed:

matplotlib graph

like image 148
Martin Evans Avatar answered May 21 '26 03:05

Martin Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!