

.. _sphx_glr_gallery_pylab_examples_stackplot_demo.py:


==============
Stackplot Demo
==============

How to create stackplots with Matplotlib.

Stackplots are generated by plotting different datasets vertically on
top of one another rather than overlapping with one another. Below we
show some examples to accomplish this with Matplotlib.



.. code-block:: python

    import numpy as np
    import matplotlib.pyplot as plt

    # Fixing random state for reproducibility
    np.random.seed(19680801)


    def fnx():
        return np.random.randint(5, 50, 10)

    y = np.row_stack((fnx(), fnx(), fnx()))
    x = np.arange(10)

    y1, y2, y3 = fnx(), fnx(), fnx()

    fig, ax = plt.subplots()
    ax.stackplot(x, y)
    plt.show()

    fig, ax = plt.subplots()
    ax.stackplot(x, y1, y2, y3)
    plt.show()




.. rst-class:: sphx-glr-horizontal


    *

      .. image:: /gallery/pylab_examples/images/sphx_glr_stackplot_demo_001.png
            :scale: 47

    *

      .. image:: /gallery/pylab_examples/images/sphx_glr_stackplot_demo_002.png
            :scale: 47




Here we'll show a slightly more complex example.



.. code-block:: python



    def layers(n, m):
        """
        Return *n* random Gaussian mixtures, each of length *m*.
        """
        def bump(a):
            x = 1 / (.1 + np.random.random())
            y = 2 * np.random.random() - .5
            z = 10 / (.1 + np.random.random())
            for i in range(m):
                w = (i / float(m) - y) * z
                a[i] += x * np.exp(-w * w)
        a = np.zeros((m, n))
        for i in range(n):
            for j in range(5):
                bump(a[:, i])
        return a

    d = layers(3, 100)

    fig, ax = plt.subplots()
    ax.stackplot(range(100), d.T, baseline='wiggle')
    plt.show()



.. image:: /gallery/pylab_examples/images/sphx_glr_stackplot_demo_003.png
    :align: center




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



.. container:: sphx-glr-footer


  .. container:: sphx-glr-download

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



  .. container:: sphx-glr-download

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

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

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