{
    "nbformat": 4,
    "nbformat_minor": 5,
    "metadata": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python",
            "name": "python"
        },
        "language_info": {
            "name": "python"
        }
    },
    "cells": [
        {
            "id": "9892d876",
            "cell_type": "markdown",
            "source": "<div class='alert alert-warning'>\n\nSciPy's interactive examples with Jupyterlite are experimental and may not always work as expected. Execution of cells containing imports may result in large downloads (up to 60MB of content for the first import from SciPy). Load times when importing from SciPy may take roughly 10-20 seconds. If you notice any problems, feel free to open an [issue](https://github.com/scipy/scipy/issues/new/choose).\n\n</div>",
            "metadata": {}
        },
        {
            "id": "6cd1a97e",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "import numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt",
            "outputs": []
        },
        {
            "id": "5301ffaf",
            "cell_type": "markdown",
            "source": "First some basic examples:\n\nCreate two evenly spaced bins in the range of the given sample, and sum the\ncorresponding values in each of those bins:\n",
            "metadata": {}
        },
        {
            "id": "4956a7c1",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "values = [1.0, 1.0, 2.0, 1.5, 3.0]\nstats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2)",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "BinnedStatisticResult(statistic=array([4. , 4.5]),\n        bin_edges=array([1., 4., 7.]), binnumber=array([1, 1, 1, 2, 2]))"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "c0af1e00",
            "cell_type": "markdown",
            "source": "Multiple arrays of values can also be passed.  The statistic is calculated\non each set independently:\n",
            "metadata": {}
        },
        {
            "id": "635821f1",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "values = [[1.0, 1.0, 2.0, 1.5, 3.0], [2.0, 2.0, 4.0, 3.0, 6.0]]\nstats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2)",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "BinnedStatisticResult(statistic=array([[4. , 4.5],\n       [8. , 9. ]]), bin_edges=array([1., 4., 7.]),\n       binnumber=array([1, 1, 1, 2, 2]))"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "117eed23",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean',\n                       bins=3)",
            "outputs": [
                {
                    "output_type": "execute_result",
                    "metadata": {},
                    "data": {
                        "text/plain": "BinnedStatisticResult(statistic=array([1., 2., 4.]),\n        bin_edges=array([1., 2., 3., 4.]),\n        binnumber=array([1, 2, 1, 2, 3]))"
                    },
                    "execution_count": null
                }
            ]
        },
        {
            "id": "f3400b0c",
            "cell_type": "markdown",
            "source": "As a second example, we now generate some random data of sailing boat speed\nas a function of wind speed, and then determine how fast our boat is for\ncertain wind speeds:\n",
            "metadata": {}
        },
        {
            "id": "4f275863",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "rng = np.random.default_rng()\nwindspeed = 8 * rng.random(500)\nboatspeed = .3 * windspeed**.5 + .2 * rng.random(500)\nbin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,\n                boatspeed, statistic='median', bins=[1,2,3,4,5,6,7])\nplt.figure()\nplt.plot(windspeed, boatspeed, 'b.', label='raw data')\nplt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,\n           label='binned statistic of data')\nplt.legend()",
            "outputs": []
        },
        {
            "id": "fb403be3",
            "cell_type": "markdown",
            "source": "Now we can use ``binnumber`` to select all datapoints with a windspeed\nbelow 1:\n",
            "metadata": {}
        },
        {
            "id": "45701692",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "low_boatspeed = boatspeed[binnumber == 0]",
            "outputs": []
        },
        {
            "id": "49d606a7",
            "cell_type": "markdown",
            "source": "As a final example, we will use ``bin_edges`` and ``binnumber`` to make a\nplot of a distribution that shows the mean and distribution around that\nmean per bin, on top of a regular histogram and the probability\ndistribution function:\n",
            "metadata": {}
        },
        {
            "id": "5014d8dd",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "x = np.linspace(0, 5, num=500)\nx_pdf = stats.maxwell.pdf(x)\nsamples = stats.maxwell.rvs(size=10000)",
            "outputs": []
        },
        {
            "id": "c347ae62",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "bin_means, bin_edges, binnumber = stats.binned_statistic(x, x_pdf,\n        statistic='mean', bins=25)\nbin_width = (bin_edges[1] - bin_edges[0])\nbin_centers = bin_edges[1:] - bin_width/2",
            "outputs": []
        },
        {
            "id": "882ca55f",
            "cell_type": "code",
            "metadata": {},
            "execution_count": null,
            "source": "plt.figure()\nplt.hist(samples, bins=50, density=True, histtype='stepfilled',\n         alpha=0.2, label='histogram of data')\nplt.plot(x, x_pdf, 'r-', label='analytical pdf')\nplt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=2,\n           label='binned statistic of data')\nplt.plot((binnumber - 0.5) * bin_width, x_pdf, 'g.', alpha=0.5)\nplt.legend(fontsize=10)\nplt.show()",
            "outputs": []
        }
    ]
}