gpt4 book ai didi

python - 尝试制作条形图,bar() 缺少 1 个必需的位置参数 : 'height'

转载 作者:行者123 更新时间:2023-12-01 00:49:16 24 4
gpt4 key购买 nike

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

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

最佳答案

对于条形图,您需要指定所有条形的 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

关于python - 尝试制作条形图,bar() 缺少 1 个必需的位置参数 : 'height' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56704332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com