{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Stackplots and streamgraphs\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Stackplots\n\nStackplots draw multiple datasets as vertically stacked areas. This is\nuseful when the individual data values and additionally their cumulative\nvalue are of interest.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.ticker as mticker\n\n# data from United Nations World Population Prospects (Revision 2019)\n# https://population.un.org/wpp/, license: CC BY 3.0 IGO\nyear = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2018]\npopulation_by_continent = {\n 'Africa': [.228, .284, .365, .477, .631, .814, 1.044, 1.275],\n 'the Americas': [.340, .425, .519, .619, .727, .840, .943, 1.006],\n 'Asia': [1.394, 1.686, 2.120, 2.625, 3.202, 3.714, 4.169, 4.560],\n 'Europe': [.220, .253, .276, .295, .310, .303, .294, .293],\n 'Oceania': [.012, .015, .019, .022, .026, .031, .036, .039],\n}\n\nfig, ax = plt.subplots()\nax.stackplot(year, population_by_continent.values(),\n labels=population_by_continent.keys(), alpha=0.8)\nax.legend(loc='upper left', reverse=True)\nax.set_title('World population')\nax.set_xlabel('Year')\nax.set_ylabel('Number of people (billions)')\n# add tick at every 200 million people\nax.yaxis.set_minor_locator(mticker.MultipleLocator(.2))\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Streamgraphs\n\nUsing the *baseline* parameter, you can turn an ordinary stacked area plot\nwith baseline 0 into a stream graph.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\ndef gaussian_mixture(x, n=5):\n \"\"\"Return a random mixture of *n* Gaussians, evaluated at positions *x*.\"\"\"\n def add_random_gaussian(a):\n amplitude = 1 / (.1 + np.random.random())\n dx = x[-1] - x[0]\n x0 = (2 * np.random.random() - .5) * dx\n z = 10 / (.1 + np.random.random()) / dx\n a += amplitude * np.exp(-(z * (x - x0))**2)\n a = np.zeros_like(x)\n for j in range(n):\n add_random_gaussian(a)\n return a\n\n\nx = np.linspace(0, 100, 101)\nys = [gaussian_mixture(x) for _ in range(3)]\n\nfig, ax = plt.subplots()\nax.stackplot(x, ys, baseline='wiggle')\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. tags::\n\n plot-type: stackplot\n level: intermediate\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }