【问题标题】:Matplotlib histogram with errorbars带误差线的 Matplotlib 直方图
【发布时间】:2012-07-31 06:26:40
【问题描述】:

我使用pyplot.hist() 函数创建了带有matplotlib 的直方图。我想在条形图中添加一个 bin 高度 (sqrt(binheight)) 的中毒误差平方根。我该怎么做?

.hist() 的返回元组包括return[2] -> 1 个 Patch 对象的列表。我只能发现可以将错误添加到通过pyplot.bar() 创建的条形图上。

【问题讨论】:

    标签: matplotlib histogram


    【解决方案1】:

    确实需要使用 bar。您可以使用hist 的输出并将其绘制为条形:

    import numpy as np
    import pylab as plt
    
    data       = np.array(np.random.rand(1000))
    y,binEdges = np.histogram(data,bins=10)
    bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
    menStd     = np.sqrt(y)
    width      = 0.05
    plt.bar(bincenters, y, width=width, color='r', yerr=menStd)
    plt.show()
    

    【讨论】:

    • 如果能在 hist() 中实现这个功能会很好。这样它就会自动计算每个 bin 的标准值。
    【解决方案2】:

    替代方案

    您还可以使用pyplot.errorbar()drawstyle 关键字参数的组合。下面的代码使用阶梯线图创建直方图。每个 bin 的中心都有一个标记,每个 bin 都有必要的泊松误差条。

    import numpy
    import pyplot
    
    x = numpy.random.rand(1000)
    y, bin_edges = numpy.histogram(x, bins=10)
    bin_centers = 0.5*(bin_edges[1:] + bin_edges[:-1])
    
    pyplot.errorbar(
        bin_centers,
        y,
        yerr = y**0.5,
        marker = '.',
        drawstyle = 'steps-mid-'
    )
    pyplot.show()
    

    我的个人意见

    在同一张图上绘制多个直方图的结果时,线图更容易区分。此外,使用yscale='log' 绘图时它们看起来更好。

    【讨论】:

    • pyplot.errorbar 中的fmt='none' 选项可以让您仅绘制误差线。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 2012-08-14
    • 2013-10-13
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多