简体   繁体   中英

I get the error: “ValueError: could not convert string to float: '$20'”

I'm new to programming and I am trying to figure out why do I get this error when I'm trying to run the code. When I only run the December 'rects2' barcode and take out the other 'rects' bars it works. but when I try to insert another 'rects' bar while adding a variable in its data string not included in the first 'rects1' bar it gives me a ValueError. Any particular reason why this is happening?

What can I do to fix it in any way if I can't 100% solve this to at least have a somewhat functioning graph?

'''
Gas chart comparing various months and the total cost for that month in gas 
purchases
'''

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

#data to plot
n_groups = 6
days = ('0','5','10','15','20','25','30')
y_pos = np.arange(len(days))
fixed_rates = 
['$60','$55','$50','$45','$40','$35','$30',
'$25','$20','$15','$10','$5','$0']
#november_data = TBD 
december_data = (fixed_rates[12],fixed_rates[6],fixed_rates[0],
fixed_rates[6],fixed_rates[6],fixed_rates[6])
january_data = (fixed_rates[12],fixed_rates[6],fixed_rates[6],
fixed_rates[8],fixed_rates[6],fixed_rates[12])

#create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.25
opacity = 0.5


rects1 = plt.bar(index + bar_width, december_data, bar_width,
             alpha=opacity,
             color='b',
             label='December')


rects2 = plt.bar(index + bar_width + bar_width, january_data, bar_width,
             alpha=opacity,
             color='gray',
             label='January')

'''
rects3 = plt.bar(index, november_data, bar_width,
             alpha=opacity,
             color='g',
             label='November')
'''

#plt.bar(y_pos, days, align='center', alpha=0.5)
plt.xticks(y_pos, days)
plt.xlabel('Days (in 5 day increments)')
plt.ylabel('Fixed rates')
plt.title('Gas costs in the past 3 months')
plt.legend()

plt.tight_layout()
plt.show()

Here is the error I get whenever I try to run it in IDLE:

Traceback (most recent call last):
File 
"C:\Users\zanec\Desktop\Udemy_Python_course\practice\gasgraphinpython.py", 
line 35, in <module>
label='January')
File "C:\Users\zanec\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 
2627, in bar
ret = ax.bar(*args, **kwargs)
File "C:\Users\zanec\Anaconda3\lib\site-packages\matplotlib\__init__.py", 
line 1710, in inner
return func(ax, *args, **kwargs)
File "C:\Users\zanec\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", 
line 2121, in bar
height = self.convert_yunits(height)
File "C:\Users\zanec\Anaconda3\lib\site-packages\matplotlib\artist.py", line 
200, in convert_yunits
return ax.yaxis.convert_units(y)
File "C:\Users\zanec\Anaconda3\lib\site-packages\matplotlib\axis.py", line 
1491, in convert_units
ret = self.converter.convert(x, self.units, self)
File "C:\Users\zanec\Anaconda3\lib\site-packages\matplotlib\category.py", 
line 53, in convert
return vals.astype('float')
ValueError: could not convert string to float: '$20'
value = '$20'

float(value)

will produce an error because of the '$' symbol

float(value.replace('$',''))

will work

propably better to not have the '$' symbol in the fixed rates array

I am not very good in matplotlib, but what I see here is, you are feeding wrong data to the plot.

fixed_rates = ['$60','$55','$50','$45','$40','$35','$30',
'$25','$20','$15','$10','$5','$0']

As you are feeding it to matplotlib, It is calculating the data and while converting it to float it is giving error.

So you need to change it to

 fixed_rates = ['60','55','50','45','40','35','30', '25','20','15','10','5','0']

or, better

fixed_rates = [6, 55, 50, 45, 40, 35, 30,  25, 20, 15, 10, 5, 0]

or,

fixed_rates = map(lambda x: float(x.replace('$', '')), fixed_rates)

If you want to show '$' sign in y-axis, you can use yticks to do that.

plt.yticks(np.arange(0, 61, 10), ['$0', '$10', '$20', '$30', '$40', '$50', '$60'])

or just modify ylabel

plt.ylabel('Fixed rates ( in dollars )')

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM