带误差条的Matplotlib直方图

17

我使用pyplot.hist()函数创建了一个带有matplotlib的直方图。我想在条形图上添加一个 bin 高度的平方根(sqrt(binheight))作为误差值。请问如何做到这一点?

.hist()函数的返回元组中包括return[2] -> 一个由1个Patch对象组成的列表。我只找到了通过 pyplot.bar() 创建的柱状图才能添加误差。

2个回答

23

确实需要使用 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()

在这里输入图片描述


1
希望在hist()中实现这一点,这样它就可以自动计算每个bin的标准差。 - Soren

9

替代方案

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

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'绘图时,它们看起来更漂亮。


1
pyplot.errorbar中使用fmt='none'选项,可以只绘制误差线。 - Kevin Powell

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