

.. _sphx_glr_auto_examples_plot_histograms.py:


==========
Histograms
==========

Load a histogram from a file, plot it, draw random samples.



.. code-block:: python


    # Author: Moritz Lotze <mlotze@km3net.de>
    # License: BSD-3

    import h5py
    import matplotlib.pyplot as plt
    import numpy as np
    import scipy.stats
    import seaborn as sns

    import km3pipe.style.moritz         # noqa







Load the histogram from a file.
a histogram is just bincounts + binlimits.



.. code-block:: python


    filename = "data/hist_example.h5"

    with h5py.File(filename, 'r') as f:
        counts = f['/hist/counts'][:]
        binlims = f['/hist/binlims'][:]

    print(counts)
    print(counts.shape)
    print(binlims)
    print(binlims.shape)





.. rst-class:: sphx-glr-script-out

 Out::

    [  5  19  40  78  77  51  27  35  82 146 190 142  77  22   9]
    (15,)
    [ 11.82382487  12.60194812  13.38007137  14.15819462  14.93631788
      15.71444113  16.49256438  17.27068763  18.04881088  18.82693413
      19.60505738  20.38318064  21.16130389  21.93942714  22.71755039
      23.49567364]
    (16,)


create a distribution object



.. code-block:: python


    hist = scipy.stats.rv_histogram((counts, binlims))








plot it



.. code-block:: python


    # make an x axis for plotting
    padding = 3
    n_points = 10000
    x = np.linspace(binlims[0] - padding, binlims[-1] + padding, n_points)

    plt.plot(x, hist.pdf(x))





.. image:: /auto_examples/images/sphx_glr_plot_histograms_001.png
    :align: center




plot the cumulative histogram



.. code-block:: python


    plt.plot(x, hist.cdf(x))





.. image:: /auto_examples/images/sphx_glr_plot_histograms_002.png
    :align: center




sample from the histogram (aka draw random variates)



.. code-block:: python


    n_sample = 30
    sample = hist.rvs(size=n_sample)







let's plot it (use seaborn to plot the data points as small vertical bars)



.. code-block:: python

    plt.hist(sample, bins='auto', alpha=.5)
    sns.rugplot(sample, color='k', linewidth=3)



.. image:: /auto_examples/images/sphx_glr_plot_histograms_003.png
    :align: center




**Total running time of the script:** ( 0 minutes  0.559 seconds)



.. container:: sphx-glr-footer


  .. container:: sphx-glr-download

     :download:`Download Python source code: plot_histograms.py <plot_histograms.py>`



  .. container:: sphx-glr-download

     :download:`Download Jupyter notebook: plot_histograms.ipynb <plot_histograms.ipynb>`

.. rst-class:: sphx-glr-signature

    `Generated by Sphinx-Gallery <https://sphinx-gallery.readthedocs.io>`_
