17

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

Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
bioslime
  • 1,821
  • 6
  • 21
  • 27

2 Answers2

23

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

bastelflp
  • 9,362
  • 7
  • 32
  • 67
imsc
  • 7,492
  • 7
  • 47
  • 69
  • 1
    Would be nice to have this implemented in hist(). So that it calculates the std automatically for each bin. – Soerendip Dec 05 '18 at 22:57
9

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

Alex
  • 9,313
  • 1
  • 39
  • 44
mtw729
  • 163
  • 1
  • 5