Numpy histogram data: Why is the length of bins vector longer than the histogram values vector?

Viewed 1072

There are two outputs to numpy.histogram:

  • hist: values of the histogram
  • bin_edges: Return the bin edges (length(hist)+1)

both are vectors but in the example below, the second vector is of length 101, which is 1 higher than the first vector, which is length 100 :

import numpy as np
from numpy.random import rand, randn

n = 100  # number of bins
X = randn(n)*.1
a,bins1 = np.histogram(X,bins=n)

The following shape error occurs if I then try plt.plot(bins1,a):

ValueError: x and y must have same first dimension, but have shapes (101,) and (100,)

Why, and how do I fix the inequal shape error so I can plot the histogram?

1 Answers

The unequal shapes occur because bin_edges, as the name implies, specifies the bin edges. Since a bin has left and right edge, bin_edges will have be of length len(bins)+1.

As already denoted in the comments, an appropriate way to plot is plt.hist

Related