{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /gallery/statistics/histogram_features\n\n# Histogram bins, density, and weight\n\nThe `.Axes.hist` method can flexibly create histograms in a few different ways,\nwhich is flexible and helpful, but can also lead to confusion. In particular,\nyou can:\n\n- bin the data as you want, either with an automatically chosen number of\n bins, or with fixed bin edges,\n- normalize the histogram so that its integral is one,\n- and assign weights to the data points, so that each data point affects the\n count in its bin differently.\n\nThe Matplotlib ``hist`` method calls `numpy.histogram` and plots the results,\ntherefore users should consult the numpy documentation for a definitive guide.\n\nHistograms are created by defining bin edges, and taking a dataset of values\nand sorting them into the bins, and counting or summing how much data is in\neach bin. In this simple example, 9 numbers between 1 and 4 are sorted into 3\nbins:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nrng = np.random.default_rng(19680801)\n\nxdata = np.array([1.2, 2.3, 3.3, 3.1, 1.7, 3.4, 2.1, 1.25, 1.3])\nxbins = np.array([1, 2, 3, 4])\n\n# changing the style of the histogram bars just to make it\n# very clear where the boundaries of the bins are:\nstyle = {'facecolor': 'none', 'edgecolor': 'C0', 'linewidth': 3}\n\nfig, ax = plt.subplots()\nax.hist(xdata, bins=xbins, **style)\n\n# plot the xdata locations on the x axis:\nax.plot(xdata, 0*xdata, 'd')\nax.set_ylabel('Number per bin')\nax.set_xlabel('x bins (dx=1.0)')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Modifying bins\n\nChanging the bin size changes the shape of this sparse histogram, so its a\ngood idea to choose bins with some care with respect to your data. Here we\nmake the bins half as wide.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "xbins = np.arange(1, 4.5, 0.5)\n\nfig, ax = plt.subplots()\nax.hist(xdata, bins=xbins, **style)\nax.plot(xdata, 0*xdata, 'd')\nax.set_ylabel('Number per bin')\nax.set_xlabel('x bins (dx=0.5)')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also let numpy (via Matplotlib) choose the bins automatically, or\nspecify a number of bins to choose automatically:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, ax = plt.subplot_mosaic([['auto', 'n4']],\n sharex=True, sharey=True, layout='constrained')\n\nax['auto'].hist(xdata, **style)\nax['auto'].plot(xdata, 0*xdata, 'd')\nax['auto'].set_ylabel('Number per bin')\nax['auto'].set_xlabel('x bins (auto)')\n\nax['n4'].hist(xdata, bins=4, **style)\nax['n4'].plot(xdata, 0*xdata, 'd')\nax['n4'].set_xlabel('x bins (\"bins=4\")')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Normalizing histograms: density and weight\n\nCounts-per-bin is the default length of each bar in the histogram. However,\nwe can also normalize the bar lengths as a probability density function using\nthe ``density`` parameter:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, ax = plt.subplots()\nax.hist(xdata, bins=xbins, density=True, **style)\nax.set_ylabel('Probability density [$V^{-1}$])')\nax.set_xlabel('x bins (dx=0.5 $V$)')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This normalization can be a little hard to interpret when just exploring the\ndata. The value attached to each bar is divided by the total number of data\npoints *and* the width of the bin, and thus the values _integrate_ to one\nwhen integrating across the full range of data.\ne.g. ::\n\n density = counts / (sum(counts) * np.diff(bins))\n np.sum(density * np.diff(bins)) == 1\n\nThis normalization is how [probability density functions](https://en.wikipedia.org/wiki/Probability_density_function) are defined in\nstatistics. If $X$ is a random variable on $x$, then $f_X$\nis is the probability density function if $P[a