尝试制作一个柱状图,bar()缺少必需的位置参数“height”。

6

我正在尝试制作一个条形图,我的代码是

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()

问题是我遇到了错误

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

所以我手动添加了它。
bp_dict = plt.bar(scores,10,labels=labels)

然而,我遇到了另一个错误。

TypeError: unhashable type: 'numpy.ndarray'

感谢您的提前帮助!
更新: 以下是得分输出结果。
[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')]

更新2: 我已更新代码。
scores = list(map(float, np.array(scores).flatten()))

我把这个放进去后出现了新的错误。
AttributeError: Unknown property labels
1个回答

7

对于条形图,您需要指定所有条形的x位置。如果没有明确的x值,则最简单的方法是使用0、1、2、3等范围,以此类推。所以,如果您要绘制N个条形图,可以使用range()生成N个x值,或使用labels作为x参数。

因此,请使用:

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


嗨,谢谢你的回答!我又遇到了一个错误:“不可哈希类型:'numpy.ndarray'”,你知道是什么原因吗? - Wolfeatspotatoes
告诉我当你执行 print(scores) 时会得到什么结果。 - Sheldore
@Wolfeatspotatoes:在绘图之前添加scores = list(map(float, np.array(scores).flatten())) - Sheldore

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接