Matplotlib histogram with errorbars
Solution 1
Indeed you need to use bar. You can use to output of hist
and plot it as a bar:
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()
Solution 2
Alternative Solution
You can also use a combination of pyplot.errorbar()
and drawstyle
keyword argument. The code below creates a plot of the histogram using a stepped line plot. There is a marker in the center of each bin and each bin has the requisite Poisson errorbar.
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()
My personal opinion
When plotting the results of multiple histograms on the the same figure, line plots are easier to distinguish. In addition, they look nicer when plotting with a yscale='log'
.
bioslime
Updated on July 09, 2022Comments
-
bioslime almost 2 years
I have created a histogram with
matplotlib
using thepyplot.hist()
function. I would like to add a Poison error square root of bin height (sqrt(binheight)
) to the bars. How can I do this?The return tuple of
.hist()
includesreturn[2]
-> a list of 1 Patch objects. I could only find out that it is possible to add errors to bars created viapyplot.bar()
. -
Kevin Powell almost 9 yearsThe
fmt='none'
option inpyplot.errorbar
will enable you just plot the error bars. -
Soren over 5 yearsWould be nice to have this implemented in hist(). So that it calculates the std automatically for each bin.