title: How to calculate the standard deviation from a histogram? (Python, Matplotlib)
body: <p>Let's say I have a data set and used matplotlib to draw a histogram of said data set.  </p>
  
  <pre><code>n, bins, patches = plt.hist(data, normed=1)
  </code></pre>
  
  <p>How do I calculate the standard deviation, using the <code>n</code> and <code>bins</code> values that <code>hist()</code> returns? I'm currently doing this to calculate the mean:  </p>
  
  <pre><code>s = 0
  for i in range(len(n)):
     s += n[i] * ((bins[i] + bins[i+1]) / 2) 
  mean = s / numpy.sum(n)
  </code></pre>
  
  <p>which seems to work fine as I get pretty accurate results. However, if I try to calculate the standard deviation like this:  </p>
  
  <pre><code>t = 0
  for i in range(len(n)):
    t += (bins[i] - mean)**2
  std = np.sqrt(t / numpy.sum(n))
  </code></pre>
  
  <p>my results are way off from what <code>numpy.std(data)</code> returns. Replacing the left bin limits with the central point of each bin doesn't change this either. I have the feeling that the problem is that the <code>n</code> and <code>bins</code> values don't actually contain <em>any</em> information on how the individual data points are distributed within each bin, but the assignment I'm working on clearly demands that I use them to calculate the standard deviation.</p>