直方图:使用for循环的Python matplotlib.bar

时间:2019-03-17 16:49:08

标签: python matplotlib histogram

尝试

我尝试使用 matplotlib 3.0.3 python3.7 中绘制一些直方图,但出现问题:

代码:

ind = np.arange(2)
width = 0.35
data = [(0.5, 0.1), (0.8, 0.3)]
for i in data:
    plt.bar(ind, i[0], width, yerr=i[1])
plt.ylabel('scratchwidth /cm')
plt.show

输出:

我期望有两个条形图,(0|0.5)(1|0.8),不确定性为0.10.3。我得到的是两个柱,两个柱均具有 y = 0.8 和不确定性 0.3 plt.bar()是否不能在for循环中使用? 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您必须将Y数组和Err数组传递给函数bar。将数据从点数组转换为Y和Err数组:

ind = np.arange(2)
width = 0.35
data = [(0.5, 0.1), (0.8, 0.3)]
y, err = list(zip(*data)) # Transpose the data array
plt.bar(ind, y, width, yerr=err)
plt.ylabel('scratchwidth /cm')
plt.show()

或者,由于您已经使用了numpy,请使用numpy数组:

....
data = np.array([(0.5, 0.1), (0.8, 0.3)])
plt.bar(ind, data[:,0], width, yerr=data[:,1])
....