{ "cells": [ { "cell_type": "markdown", "metadata": { "toc": true }, "source": [ "

Table of Contents

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matplotlib\n", "\n", "With `matplotlib` one can easily create professional graphs and plots using numpy, scipy or pandas data.\n", "\n", "Only brief overview here, many nice examples in: http://scipy-cookbook.readthedocs.org/items/idx_matplotlib_simple_plotting.html\n", "\n", "\n", "\n", "`matplotlib` can be used both for\n", "* interactive work to analyse data and investigate properties\n", "* use in scripts programs which generate predefined graphs and store it in one of the standard graphic formats *(PS, EPS, SVG, PNG, ...)*\n", "\n", "When working in Jupyter one usually shows the graphs directly in the notebook:\n", "* default or directive `%matplotlib inline`\n", "\n", "Or one uses separate graphics window:\n", "* directive `%matplotlib qt` (on Linux, some extra functionality like zooming or storing)\n", "\n", "More recently the package `ipympl` was introduced which provides additional interactive functionality for inline graphs in notebooks\n", "* directive `%matplotlib widget`\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simple line-plot example\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import numpy as np\n", "# common matplotlib shorthands\n", "import matplotlib.pyplot as plt\n", "x = np.linspace(0, 10, 100)\n", "\n", "fig = plt.figure()\n", "plt.plot(x, np.sin(x))\n", "plt.plot(x, np.cos(x));" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Storing figures" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.linspace(0, 10, 100)\n", "fig = plt.figure() # get handle to matplotlib figure first\n", "plt.plot(x, np.sin(x),'-')\n", "plt.plot(x, np.cos(x),'--')\n", "fig.savefig('my_figure.png') # call save method for this figure" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!ls -l my_figure.png # check it got actually created" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Adjusting the plot:\n", "#### Labels, Titles and Legend" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t = np.linspace(0, 5, 100)\n", "v1 = np.cos(2*2*np.pi*t)\n", "v2 = np.sin(2*np.pi*t)\n", "fig = plt.figure()\n", "plt.plot(t, v1,'-',label='Voltage-1')\n", "plt.plot(t, v2,'--',label='Voltage-2')\n", "\n", "plt.xlabel('time (s)') # x-axis\n", "plt.ylabel('voltage (mV)')# y-axis\n", "plt.title('About as simple as it gets, folks') # title header\n", "plt.grid(True)\n", "plt.legend();" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### colors and line-styles" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure()\n", "plt.plot(x, np.sin(x - 0), color='blue') # specify color by name\n", "plt.plot(x, np.sin(x - 1), color='g') # short color code (rgbcmyk)\n", "plt.plot(x, np.sin(x - 2), color='0.75') # Grayscale between 0 and 1\n", "plt.plot(x, np.sin(x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF)\n", "plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 to 1\n", "plt.plot(x, np.sin(x - 5), color='chartreuse'); # all HTML color names supported" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure()\n", "plt.plot(x, x + 0, linestyle='solid')\n", "plt.plot(x, x + 1, linestyle='dashed')\n", "plt.plot(x, x + 2, linestyle='dashdot')\n", "plt.plot(x, x + 3, linestyle='dotted');\n", "\n", "# For short, you can use the following codes:\n", "plt.plot(x, x + 4, linestyle='-') # solid\n", "plt.plot(x, x + 5, linestyle='--') # dashed\n", "plt.plot(x, x + 6, linestyle='-.') # dashdot\n", "plt.plot(x, x + 7, linestyle=':'); # dotted" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure()\n", "# compact combined form ...\n", "plt.plot(x, x + 0, '-g') # solid green\n", "plt.plot(x, x + 1, '--c') # dashed cyan\n", "plt.plot(x, x + 2, '-.k') # dashdot black\n", "plt.plot(x, x + 3, ':r'); # dotted red" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### explicit axis limits" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure()\n", "plt.plot(x, np.sin(x))\n", "plt.axis([-1, 11, -1.5, 1.5]); # just a list with xmin, xmax, ymin, ymax" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scatter plots\n", "For simple cases one can just use `plt.plot` with key `o` :\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.linspace(0, 10, 30)\n", "fig = plt.figure() # get handle to matplotlib figure first\n", "plt.plot(x, np.sin(x),'o')\n", "plt.plot(x, np.cos(x),'+');" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# marker demo\n", "# plot 5 random x,y pairs for each std marker type\n", "#\n", "fig = plt.figure()\n", "for marker in ['o', '.', 'v', '^', '<', '>', 's', 'd']:\n", " plt.plot(np.random.random(5), np.random.random(5), marker,\n", " label=\"marker='{0}'\".format(marker))\n", "plt.legend(numpoints=1)\n", "plt.xlim(0, 1.8);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### More sophisticated plots with plt.scatter\n", "\n", "* allows variable symbol size\n", "* and variable color\n", "\n", "$\\rightarrow$ visualize **3rd** and **4th** dimension" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.random.randn(100) # gauss rnd\n", "y = np.random.randn(100)\n", "colors = np.random.random(100) # uniform rand\n", "sizes = 1000 * np.random.random(100)\n", "fig = plt.figure()\n", "plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,\n", " cmap='viridis')\n", "plt.colorbar(); # show color scale" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plotting error-bars\n", "\n", "Scientific data, in particular in physics, often has errors associated to the y-coordinate (sometimes also to x) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.linspace(0, 10, 50)\n", "y = np.sin(x) + 0.5*np.random.randn(50)\n", "fig = plt.figure()\n", "#plt.errorbar(x, y, 0.7, fmt='ob'); # fixed error in y, can also be array\n", "plt.errorbar(x, y, 0.5*y, fmt='ob');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Histograms\n", "Fundamental plot type to visualize data distributions, mostly in 1D but also 2D or even 3D" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# simple 1d histogram\n", "#\n", "mu, sigma = 100, 15\n", "x = np.random.normal(mu,sigma,10000)\n", "fig = plt.figure()\n", "# the histogram of the data\n", "plt.hist(x,bins=50, range=(80,120)) # args: array to fill, num-bins\n", "\n", "plt.title(r'$\\mathrm{Histogram\\ of\\ IQ:}\\ \\mu=100,\\ \\sigma=15$'); # Latex syntax for math\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.hist?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Some more options for Histograms\n", "Many options how to fill and display histograms" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# demonstrate overlaying several histos\n", "x1 = np.random.normal(0, 0.8, 1000)\n", "x2 = np.random.normal(-2, 1, 1000)\n", "x3 = np.random.normal(3, 2, 1000)\n", "\n", "# Options: \n", "# density=True -- normalized to 1\n", "# alpha=0.3 -- transparency of fill\n", "# histtype='stepfilled' -- only filled bar, no line in between\n", "kwargs = dict(histtype='stepfilled', alpha=0.3, density=True, bins=40)\n", "fig = plt.figure()\n", "plt.hist(x1, **kwargs)\n", "plt.hist(x2, **kwargs)\n", "plt.hist(x3, **kwargs);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2d histograms\n", "2 variables can of course be plotted as x-y point plot:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "mean =[0, 0]\n", "cov = [[1, 1], [1, 2]]\n", "x, y = np.random.multivariate_normal(mean, cov, 10000).T # generate correlated random points\n", "fig = plt.figure()\n", "plt.plot(x,y,'.');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But often more instructive to use *2D histo*\n", "* 2D area split in cells\n", "* histogram counts entries in cells\n", "* visualize as color shade" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "fig = plt.figure()\n", "plt.hist2d(x, y, bins=30, cmap='Blues')\n", "cb = plt.colorbar()\n", "cb.set_label('counts in bin')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interactive Plots\n", "Using `interact` from `ipywidgets` package one can create graphs with interactive control" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "%matplotlib inline\n", "\n", "from ipywidgets import interact\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "x = np.linspace(0, 2 * np.pi,100)\n", "fig = plt.figure(1,figsize=(6,4))\n", "\n", "def update(w = 1.0):\n", " plt.plot(x, np.sin(w*x))\n", " plt.show()\n", "\n", "interact(update, w=(0.5, 10, 0.1), continuous_update=False); # continuous_update not respected" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Other features\n", "\n", "Of course there are many more features in `matplotlib`, such as\n", "* multiple subplots\n", "* 3D visualization\n", "* styles\n", "* annotations\n", "* ...\n", "\n", "We will see some of that in the following chapters." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "@webio": { "lastCommId": null, "lastKernelId": null }, "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.8.10" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": true, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "261px" }, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }