Matplotlib histogram with errorbars

35,333

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

enter image description here

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'.

Share:
35,333
bioslime
Author by

bioslime

Updated on July 09, 2022

Comments

  • bioslime
    bioslime almost 2 years

    I have created a histogram with matplotlib using the pyplot.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() includes return[2] -> a list of 1 Patch objects. I could only find out that it is possible to add errors to bars created via pyplot.bar().

  • Kevin Powell
    Kevin Powell almost 9 years
    The fmt='none' option in pyplot.errorbar will enable you just plot the error bars.
  • Soren
    Soren over 5 years
    Would be nice to have this implemented in hist(). So that it calculates the std automatically for each bin.