Trying to make a barchart, bar() missing 1 required positional argument: 'height'

Viewed 28810

I am trying to make a barchart, my code is

data = np.genfromtxt("ca1_data/distance.csv",
               delimiter=',',skip_header=1,
               dtype=[('Year','i4'),('Mode','U50'),('Distance','U10')],
               missing_values=['na','-'],filling_values=[0])
years = np.arange(5)
scores = [(data[(data['Mode']=='MRT') & (data['Year']>=2010)]['Distance']), 
          (data[(data['Mode']=='Bus') & (data['Year']>=2010)]['Distance'])]
labels = np.arange(2010,2015)
print(scores)
fig = plt.figure(figsize=(20,10))
ax1 = fig.add_subplot(111)
ax1.set_xticklabels(labels, fontsize=10)
plt.title(title)
plt.xlabel('Years')
plt.ylabel('Distance')
bp_dict = plt.bar(scores,10,labels=labels)
plt.show()

the problem is I got the error

bar() missing 1 required positional argument: 'height'

So I added it manually

bp_dict = plt.bar(scores,10,labels=labels)

However, I got another error

TypeError: unhashable type: 'numpy.ndarray'

Thanks in advance!

Update: This is what the ouput of scores is

[array(['10.3', '10', '9.6', '9.5', '9.2'], dtype='<U10'), array(['4.8', '4.5', '4.4', '4.3', '4.3'], dtype='<U10')]

Update2: I updated the code

scores = list(map(float, np.array(scores).flatten()))

I got new error after putting this

AttributeError: Unknown property labels
1 Answers

For bar chart, you need to specify the x-location of all the bars. The simplest way if you have no explicit x-values is to use a range 0, 1, 2, 3, ... and so on. So if you have N bars to plot, you can generate N x-values using range() or use labels as the x-argument

Therefore, use

labels =  np.arange(2010,2015)

scores = [np.array(['10.3', '10', '9.6', '9.5', '9.2'], dtype='<U10'), 
          np.array(['4.8', '4.5', '4.4', '4.3', '4.3'], dtype='<U10')]

bp_dict = plt.bar(labels, list(map(float, scores[0])), align='edge', width=-0.4)
bp_dict = plt.bar(labels, list(map(float, scores[1])), align='edge', width=0.4)

enter image description here

Related