Home > Net >  Python Barplot ValueError: could not convert string to float:
Python Barplot ValueError: could not convert string to float:

Time:11-10

I try to plot a simple barplot in Python, but when I run the code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x=['A','B','C','D','E','F','G','H','I','J']
y=[47, 23, 27,  0, 82,  7, 46, 92, 36, 76]
plt.bar(x,y)
plt.xlabel('Categories')
plt.ylabel("Values")
plt.title('Categories Bar Plot')
plt.show()

I get an error message:

ValueError: could not convert string to float: 'A'

I don't know why this does not work, especially because it's an exact copy of an example from a website which should work.

CodePudding user response:

Which pandas/matplotlib versions are you using? Have you made sure to use a clean environment?

You code works fine for me.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x=['A','B','C','D','E','F','G','H','I','J']
y=[47, 23, 27,  0, 82,  7, 46, 92, 36, 76]
plt.bar(x,y)
plt.xlabel('Categories')
plt.ylabel("Values")
plt.title('Categories Bar Plot')
plt.show()

output:

bar plot

CodePudding user response:

Turns out, I use matplotlib 1.5.1 and I can't upgrade it because of reasons I can't write here. But I wrote a workaround I wanted to share with the community:

x1=['A','B','C','D','E','F','G','H','I','J']
N=0
x2=[]
for i in range(len(x1)):
    x2.append(N)
    N =1
y=[47, 23, 27,  0, 82,  7, 46, 92, 36, 76]
plt.bar(x2,y)
plt.xlabel('Categories')
plt.ylabel("Values")
plt.title('Categories Bar Plot')
plt.xticks(np.arange(0.5, len(x2) 0.5), list(x1), rotation=90, size = '10')
plt.show()
  • Related