带误差线的 Matplotlib 直方图

问题描述 投票:0回答:2

我使用

matplotlib
函数创建了带有
pyplot.hist()
的直方图。我想向条形图添加箱高度 (
sqrt(binheight)
) 的毒害误差平方根。我该怎么做?

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

matplotlib histogram
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()

enter image description here


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

© www.soinside.com 2019 - 2024. All rights reserved.