Histogram-related functions
Function | histogram |
Compute the histogram of a dataset. |
Function | histogram |
Function to calculate only the edges of the bins used by the histogram function. |
Function | histogramdd |
Compute the multidimensional histogram of some data. |
Variable | array |
Undocumented |
Function | _get |
Computes the bins used internally by histogram . |
Function | _get |
Determine the outer bin edges to use, from either the data or the range argument |
Function | _hist |
Histogram bin estimator that uses the minimum width of the Freedman-Diaconis and Sturges estimators if the FD bin width is non-zero. If the bin width from the FD estimator is 0, the Sturges estimator is used. |
Function | _hist |
Doane's histogram bin estimator. |
Function | _hist |
The Freedman-Diaconis histogram bin estimator. |
Function | _hist |
Rice histogram bin estimator. |
Function | _hist |
Scott histogram bin estimator. |
Function | _hist |
Square root histogram bin estimator. |
Function | _hist |
Histogram bin estimator based on minimizing the estimated integrated squared error (ISE). |
Function | _hist |
Sturges histogram bin estimator. |
Function | _histogram |
Undocumented |
Function | _histogram |
Undocumented |
Function | _histogramdd |
Undocumented |
Function | _ptp |
Peak-to-peak value of x. |
Function | _ravel |
Check a and weights have matching shapes, and ravel both |
Function | _search |
Like searchsorted , but where the last item in v is placed on the right. |
Function | _unsigned |
Subtract two values where a >= b, and produce an unsigned result |
Variable | _hist |
Undocumented |
def histogram(a, bins=10, range=None, density=None, weights=None): (source) ¶
Compute the histogram of a dataset.
See Also
histogramdd
, bincount
, searchsorted
, digitize
, histogram_bin_edges
Notes
All but the last (righthand-most) bin is half-open. In other words,
if bins
is:
[1, 2, 3, 4]
then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.
Examples
>>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3]) (array([0, 2, 1]), array([0, 1, 2, 3])) >>> np.histogram(np.arange(4), bins=np.arange(5), density=True) (array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) (array([1, 4, 1]), array([0, 1, 2, 3]))
>>> a = np.arange(5) >>> hist, bin_edges = np.histogram(a, density=True) >>> hist array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]) >>> hist.sum() 2.4999999999999996 >>> np.sum(hist * np.diff(bin_edges)) 1.0
Automated Bin Selection Methods example, using 2 peak random data with 2000 points:
>>> import matplotlib.pyplot as plt >>> rng = np.random.RandomState(10) # deterministic random data >>> a = np.hstack((rng.normal(size=1000), ... rng.normal(loc=5, scale=2, size=1000))) >>> _ = plt.hist(a, bins='auto') # arguments are passed to np.histogram >>> plt.title("Histogram with 'auto' bins") Text(0.5, 1.0, "Histogram with 'auto' bins") >>> plt.show()
Parameters | |
a:array_like | Input data. The histogram is computed over the flattened array. |
bins:int or sequence of scalars or str , optional | If
New in version 1.11.0.
If |
range:(float , float) , optional | The lower and upper range of the bins. If not provided, range
is simply (a.min(), a.max()). Values outside the range are
ignored. The first element of the range must be less than or
equal to the second. range affects the automatic bin
computation as well. While bin width is computed to be optimal
based on the actual data within range , the bin count will fill
the entire range including portions containing no data. |
density:bool , optional | If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function. |
weights:array_like , optional | An array of weights, of the same shape as a . Each value in
a only contributes its associated weight towards the bin count
(instead of 1). If density is True, the weights are
normalized, so that the integral of the density over the range
remains 1. |
Returns | |
def histogram_bin_edges(a, bins=10, range=None, weights=None): (source) ¶
Function to calculate only the edges of the bins used by the histogram
function.
See Also
Notes
The methods to estimate the optimal number of bins are well founded
in literature, and are inspired by the choices R provides for
histogram visualisation. Note that having the number of bins
proportional to n1 ⁄ 3 is asymptotically optimal, which is
why it appears in most estimators. These are simply plug-in methods
that give good starting points for number of bins. In the equations
below, h is the binwidth and nh is the number of
bins. All estimators that compute bin counts are recast to bin width
using the ptp
of the data. The final bin count is obtained from
np.round(np.ceil(range / h)). The final bin width is often less
than what is returned by the estimators below.
- 'auto' (maximum of the 'sturges' and 'fd' estimators)
- A compromise to get a good value. For small datasets the Sturges value will usually be chosen, while larger datasets will usually default to FD. Avoids the overly conservative behaviour of FD and Sturges for small and large datasets respectively. Switchover point is usually a.size ≈ 1000.
- 'fd' (Freedman Diaconis Estimator)
- h = 2(IQR)/(n1 ⁄ 3)
The binwidth is proportional to the interquartile range (IQR) and inversely proportional to cube root of a.size. Can be too conservative for small datasets, but is quite good for large datasets. The IQR is very robust to outliers.
- 'scott'
- h = σ3√((24√(π))/(n))
The binwidth is proportional to the standard deviation of the data and inversely proportional to cube root of x.size. Can be too conservative for small datasets, but is quite good for large datasets. The standard deviation is not very robust to outliers. Values are very similar to the Freedman-Diaconis estimator in the absence of outliers.
- 'rice'
- nh = 2n1 ⁄ 3
The number of bins is only proportional to cube root of a.size. It tends to overestimate the number of bins and it does not take into account data variability.
- 'sturges'
- nh = log2(n) + 1
The number of bins is the base 2 log of a.size. This estimator assumes normality of data and is too conservative for larger, non-normal datasets. This is the default method in R's hist method.
- 'doane'
- nh = 1 + log2(n) + log2⎛⎝1 + (|g1|)/(σg1)⎞⎠g1 = mean⎡⎣⎛⎝(x − μ)/(σ)⎞⎠3⎤⎦σg1 = √((6(n − 2))/((n + 1)(n + 3)))
An improved version of Sturges' formula that produces better estimates for non-normal datasets. This estimator attempts to account for the skew of the data.
- 'sqrt'
- nh = √(n)
The simplest and fastest estimator. Only takes into account the data size.
Examples
>>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5]) >>> np.histogram_bin_edges(arr, bins='auto', range=(0, 1)) array([0. , 0.25, 0.5 , 0.75, 1. ]) >>> np.histogram_bin_edges(arr, bins=2) array([0. , 2.5, 5. ])
For consistency with histogram, an array of pre-computed bins is passed through unmodified:
>>> np.histogram_bin_edges(arr, [1, 2]) array([1, 2])
This function allows one set of bins to be computed, and reused across multiple histograms:
>>> shared_bins = np.histogram_bin_edges(arr, bins='auto') >>> shared_bins array([0., 1., 2., 3., 4., 5.])
>>> group_id = np.array([0, 1, 1, 0, 1, 1, 0, 1, 1]) >>> hist_0, _ = np.histogram(arr[group_id == 0], bins=shared_bins) >>> hist_1, _ = np.histogram(arr[group_id == 1], bins=shared_bins)
>>> hist_0; hist_1 array([1, 1, 0, 1, 0]) array([2, 0, 1, 1, 2])
Which gives more easily comparable results than using separate bins for each histogram:
>>> hist_0, bins_0 = np.histogram(arr[group_id == 0], bins='auto') >>> hist_1, bins_1 = np.histogram(arr[group_id == 1], bins='auto') >>> hist_0; hist_1 array([1, 1, 1]) array([2, 1, 1, 2]) >>> bins_0; bins_1 array([0., 1., 2., 3.]) array([0. , 1.25, 2.5 , 3.75, 5. ])
Parameters | |
a:array_like | Input data. The histogram is computed over the flattened array. |
bins:int or sequence of scalars or str , optional | If If
|
range:(float , float) , optional | The lower and upper range of the bins. If not provided, range
is simply (a.min(), a.max()). Values outside the range are
ignored. The first element of the range must be less than or
equal to the second. range affects the automatic bin
computation as well. While bin width is computed to be optimal
based on the actual data within range , the bin count will fill
the entire range including portions containing no data. |
weights:array_like , optional | An array of weights, of the same shape as a . Each value in
a only contributes its associated weight towards the bin count
(instead of 1). This is currently not used by any of the bin estimators,
but may be in the future. |
Returns | |
array of dtype float | bin_edges - The edges to pass into histogram |
def histogramdd(sample, bins=10, range=None, density=None, weights=None): (source) ¶
Compute the multidimensional histogram of some data.
See Also
histogram
- 1-D histogram
histogram2d
- 2-D histogram
Examples
>>> r = np.random.randn(100,3) >>> H, edges = np.histogramdd(r, bins = (5, 8, 4)) >>> H.shape, edges[0].size, edges[1].size, edges[2].size ((5, 8, 4), 6, 9, 5)
Parameters | |
sample:(N , D) array, or ( N , D) array_like | The data to be histogrammed. Note the unusual interpretation of sample when an array_like:
The first form should be preferred. |
bins:sequence or int , optional | The bin specification:
|
range:sequence , optional | A sequence of length D, each an optional (lower, upper) tuple giving
the outer bin edges to be used if the edges are not given explicitly in
bins .
An entry of None in the sequence results in the minimum and maximum
values being used for the corresponding dimension.
The default, None, is equivalent to passing a tuple of D None values. |
density:bool , optional | If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_volume. |
weights:(N , )array_like, optional | An array of values w_i weighing each sample (x_i, y_i, z_i, ...) .
Weights are normalized to 1 if density is True. If density is False,
the values of the returned histogram are equal to the sum of the
weights belonging to the samples falling into each bin. |
Returns | |
|
Histogram bin estimator that uses the minimum width of the Freedman-Diaconis and Sturges estimators if the FD bin width is non-zero. If the bin width from the FD estimator is 0, the Sturges estimator is used.
The FD estimator is usually the most robust method, but its width
estimate tends to be too large for small x
and bad for data with limited
variance. The Sturges estimator is quite good for small (<1000) datasets
and is the default in the R language. This method gives good off-the-shelf
behaviour.
If there is limited variance the IQR can be 0, which results in the FD bin width being 0 too. This is not a valid bin width, so np.histogram_bin_edges chooses 1 bin instead, which may not be optimal. If the IQR is 0, it's unlikely any variance-based estimators will be of use, so we revert to the Sturges estimator, which only uses the size of the dataset in its calculation.
See Also
Parameters | |
x:array_like | Input data that is to be histogrammed, trimmed to range. May not be empty. |
range | Undocumented |
Returns | |
hAn estimate of the optimal bin width for the given data. |
Doane's histogram bin estimator.
Improved version of Sturges' formula which works better for non-normal data. See stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning
Parameters | |
x:array_like | Input data that is to be histogrammed, trimmed to range. May not be empty. |
range | Undocumented |
Returns | |
hAn estimate of the optimal bin width for the given data. |
The Freedman-Diaconis histogram bin estimator.
The Freedman-Diaconis rule uses interquartile range (IQR) to estimate binwidth. It is considered a variation of the Scott rule with more robustness as the IQR is less affected by outliers than the standard deviation. However, the IQR depends on fewer points than the standard deviation, so it is less accurate, especially for long tailed distributions.
If the IQR is 0, this function returns 0 for the bin width. Binwidth is inversely proportional to the cube root of data size (asymptotically optimal).
Parameters | |
x:array_like | Input data that is to be histogrammed, trimmed to range. May not be empty. |
range | Undocumented |
Returns | |
hAn estimate of the optimal bin width for the given data. |
Rice histogram bin estimator.
Another simple estimator with no normality assumption. It has better performance for large data than Sturges, but tends to overestimate the number of bins. The number of bins is proportional to the cube root of data size (asymptotically optimal). The estimate depends only on size of the data.
Parameters | |
x:array_like | Input data that is to be histogrammed, trimmed to range. May not be empty. |
range | Undocumented |
Returns | |
hAn estimate of the optimal bin width for the given data. |
Scott histogram bin estimator.
The binwidth is proportional to the standard deviation of the data and inversely proportional to the cube root of data size (asymptotically optimal).
Parameters | |
x:array_like | Input data that is to be histogrammed, trimmed to range. May not be empty. |
range | Undocumented |
Returns | |
hAn estimate of the optimal bin width for the given data. |
Square root histogram bin estimator.
Bin width is inversely proportional to the data size. Used by many programs for its simplicity.
Parameters | |
x:array_like | Input data that is to be histogrammed, trimmed to range. May not be empty. |
range | Undocumented |
Returns | |
hAn estimate of the optimal bin width for the given data. |
Histogram bin estimator based on minimizing the estimated integrated squared error (ISE).
The number of bins is chosen by minimizing the estimated ISE against the unknown true distribution. The ISE is estimated using cross-validation and can be regarded as a generalization of Scott's rule. https://en.wikipedia.org/wiki/Histogram#Scott.27s_normal_reference_rule
This paper by Stone appears to be the origination of this rule. http://digitalassets.lib.berkeley.edu/sdtr/ucb/text/34.pdf
Parameters | |
x:array_like | Input data that is to be histogrammed, trimmed to range. May not be empty. |
range:(float , float) | The lower and upper range of the bins. |
Returns | |
hAn estimate of the optimal bin width for the given data. |
Sturges histogram bin estimator.
A very simplistic estimator based on the assumption of normality of the data. This estimator has poor performance for non-normal data, which becomes especially obvious for large data sets. The estimate depends only on size of the data.
Parameters | |
x:array_like | Input data that is to be histogrammed, trimmed to range. May not be empty. |
range | Undocumented |
Returns | |
hAn estimate of the optimal bin width for the given data. |
Peak-to-peak value of x.
This implementation avoids the problem of signed integer arrays having a peak-to-peak value that cannot be represented with the array's data type. This function returns an unsigned value for signed integer arrays.
Like searchsorted
, but where the last item in v
is placed on the right.
In the context of a histogram, this makes the last bin edge inclusive