{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to the `matplotlib` library\n", "\n", "*This notebook is taken from a course of Numerical Physics at Ecole Polytechnique, many thanks to his author Michel Ferrero (CPHT, Ecole Polytechnique) for his authorisation to distribute it.*\n", "\n", "`matplotlib` is a python plotting library that produces publication quality figures in\n", "a variety of formats. The website for the project is\n", "[matplotlib.org](http://www.matplotlib.org). In order to start using `matplotlib` in your notebooks you must\n", "add the following lines in the beginning of your notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "\n", "# You can add the lines below to make the figures larger\n", "# import matplotlib as mpl\n", "# mpl.rcParams['savefig.dpi']=100 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The second line is importing the relevant part of the ```matplotlib``` library under the\n", "name ```plt```. The first line is not a ```python``` command, it just tells the notebook that\n", "the output of plotting commands should be integrated directly into the notebook. This is\n", "what the word ```inline``` means.\n", "\n", "The project aims to have a similar syntax to ```Matlab```, so if you are familiar with that,\n", "you should be able to quickly get used to ```matplotlib```, and if you are not, you will notice\n", "that the syntax is quite self-explanatory.\n", "\n", "## A first example\n", "\n", "The code below is the first example plotting the cosine function in the interval\n", "$[ 0, 2\\pi ]$." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "x_points = np.linspace(0, 2*np.pi, 30)\n", "y_points = np.cos(x_points)\n", "\n", "plt.plot(x_points, y_points)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Making plots pretty\n", "\n", "If you want to plot several data lines, just call the `plot` function several\n", "times. Then you can work on the color and style of the lines by adding\n", "arguments to the `plot` function as below. You can also see how label,\n", "legends, etc. are added. The commands are self-explanatory." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "x_points = np.linspace(0, 2*np.pi, 30)\n", "y1_points = np.cos(x_points)\n", "y2_points = np.sin(x_points)\n", "\n", "# The plot with line styling\n", "plt.plot(x_points, y1_points, color='tab:blue', linestyle='-', linewidth=3, marker='o', label=\"cosine\")\n", "plt.plot(x_points, y2_points, color='tab:red', linestyle='--', linewidth=2, marker='x', label=\"sine\")\n", "\n", "# Add title, labels, etc.\n", "plt.title(\"Two functions\", fontsize=22)\n", "plt.xlabel(r\"$\\theta$\", fontsize=18)\n", "plt.ylabel(r\"$\\cos(\\theta)$, $\\sin(\\theta)$\", fontsize=18)\n", "plt.legend(fontsize=16)\n", "plt.xlim(0, 2*np.pi)\n", "plt.ylim(-1.2, 1.2)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Shortcut style\n", "\n", "Instead of specifying several arguments to describe the style of a line, you can\n", "use a shortcut notation:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "x_points = np.linspace(0, 2*np.pi, 30)\n", "y_points = np.cos(x_points)\n", "\n", "# look at the shortcut style\n", "plt.plot(x_points, y_points, 'o-r', lw=2) # o-r means use circles, a solid line and red color" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## More examples\n", "\n", "In principle, the examples above are enough for your needs in this lecture. Below\n", "are some more examples that you can look at. You can in particular see\n", "how the `subplot` command works." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xr = np.arange(0, 3, 0.1)\n", "yr1 = np.exp(xr) * (np.sin(5 * xr))\n", "yr2 = np.exp(xr) * (np.cos(5 * xr))\n", "plt.figure(1)\n", "plt.plot(xr, yr1, '-r', lw=3, label='a first curve')\n", "plt.plot(xr, yr2, '--b', lw=3, label='$e^{x} \\cos(5 x)$')\n", "plt.legend()\n", "plt.xlabel('time $t$')\n", "plt.ylabel('$\\int \\, \\cos(t) $')\n", "\n", "plt.figure(2)\n", "plt.plot(xr, yr1*3., '-.b^', lw=1, label='a second curve')\n", "plt.legend()\n", "plt.xlabel('time $t$')\n", "plt.ylabel('$\\int \\, \\cos(t) $')\n", "\n", "\n", "plt.figure(3)\n", "plt.subplot(211)\n", "plt.plot(xr, yr1,'-r', lw=3, label='a first curve')\n", "plt.legend()\n", "plt.ylabel('$\\int \\, \\cos(t) $')\n", "plt.subplot(212)\n", "plt.plot(xr, yr2, '--b', lw=3, label='$e^{x} \\cos(5 x)$')\n", "plt.legend()\n", "plt.xlabel('time $t$')\n", "plt.ylabel('$\\int \\, \\cos(t) $')\n", "\n", "\n", "plt.figure(4)\n", "\n", "plt.subplot(121)\n", "plt.title('My title')\n", "plt.plot(xr, yr1, '-r', lw=3, label='a first curve')\n", "plt.legend()\n", "plt.ylabel('$\\int \\, \\cos(t) $')\n", "plt.xlabel('time $t$')\n", "plt.subplot(122)\n", "plt.grid(True)\n", "plt.plot(xr, yr2, '--b', lw=3, label='$e^{x} \\cos(5 x)$')\n", "plt.legend()\n", "plt.xlabel('time $t$')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Animations\n", "matplotlib can also create animations. Only in matplotlib version 1.5.1+ can the animations be embedded in a notebook. For earlier versions, you can display the animation in another window or save to an mp4." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from matplotlib.animation import FuncAnimation\n", "%matplotlib notebook\n", "\n", "# function to be animated\n", "def func(x, phi):\n", " return np.exp(-x**2 / 4) * np.cos(3*x + phi)\n", "\n", "# updates what is plotted, i is current frame number\n", "def update_line(i):\n", " phi = 2*np.pi * i / 100\n", " x = np.linspace(-7, 7, 500)\n", " y = func(x, phi)\n", " line.set_data(x, y)\n", " return line,\n", "\n", "# create the figure, set axis limits, draw an empty plot\n", "fig, ax = plt.subplots()\n", "ax.set_xlim(-7, 7)\n", "ax.set_ylim(-1, 1)\n", "line, = ax.plot([], [], lw=2)\n", "\n", "# animate\n", "anim = FuncAnimation(fig, update_line, interval=10)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## More information\n", "\n", "`matplotlib` can do an incredible number of things. Pretty much any (especially 2d) plot\n", "you can think of. The best strategy is usually to look at examples (as those in the\n", "gallery of the `matplotlib` website) and see the code that produced them. Then you can\n", "adapt them to your needs.\n", "\n", "- This is the [matplotlib introduction](http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html)\n", " of the scipy lectures.\n", "- You can look at the documentation on the [matplotlib](http://matplotlib.org) website." ] } ], "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.7.3" } }, "nbformat": 4, "nbformat_minor": 1 }