### Navigation

- index
- modules |
- home|
- examples|
- tutorials|
- pyplot|
- docs »

# 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.

    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()

Here we’ll show a slightly more complex example.

    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()

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

Generated by Sphinx-Gallery