【问题标题】:Histograms: Python matplotlib.bar using for loop直方图:Python matplotlib.bar 使用 for 循环
【发布时间】:2019-03-17 16:49:07
【问题描述】:

尝试

我尝试使用 ma​​tplotlib 3.0.3python3.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.80.3 的不确定性。 plt.bar() 不能在 for 循环中工作吗? 我该如何解决这个问题?

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    您必须将 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])
    ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-10
      • 2021-11-07
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多