{ "metadata": { "name": "", "signature": "sha256:088412d22b7dee53bb7a79c9851ee0514167976fa12ff258af0cdf9e5cc95867" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "

Plotting and Visualization

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

This tutorial is prepared by ACM Student Chapter of King Abdullah University of Science and Technology (KAUST).
\n", "Parts of this tutorial re-use Scientific Python lectures by Robert Johansson linsensed under Creative Commons Attribution 3.0.\n", "

\n", "


" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Matplotlib

\n", "\n", "[`Matplotlib`](http://matplotlib.org/) is the basic package of Python for plotting." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "import numpy as np" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first line above ensures that our plots appear in the browser, instead in a separate window. The other import pyplot package\n", "\n", "Let's see a very simple example. Suppose we want to plot the function $\\sin(\\exp(x))$ on the interval $x\\in(0,\\pi)$. We'll want to use the NumPy functions of the sine and exponential functions. (Note: the math module operates only on scalars so we *should* use NumPy in such cases)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = np.linspace(0,np.pi,1000)\n", "f = np.sin(np.exp(x))\n", "g = np.cos(2*x)\n", "plt.plot(x,f)\n", "plt.plot(x,g)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are several ways to format a plot in python. Here we just mention only the basic functionality. It's straightforward to use them and you will generally only get into its advanced functionality if you are customizing the look of a plot for a publication. Matplotlib documentation is very good, have a look [here](http://matplotlib.sourceforge.net/users/pyplot_tutorial.html). You can also read [this tutorial](http://www.loria.fr/~rougier/teaching/matplotlib) for an easy start. More references are listed at the end of this tutorial." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following code does the basic formatting for the plot above:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure(figsize=(10,6), dpi=300) # changing figure's shape\n", "plt.xlim(x.min()-0.1, x.max()+0.1) # adjusting horizonatal axis limits\n", "plt.ylim(f.min()-0.1, f.max()+0.1) # adjusting vertical axis limits\n", "plt.xticks([0, np.pi/2, np.pi],[r'$-\\pi$', r'$-\\pi/2$', r'$0$', r'$+\\pi/2$', r'$+\\pi$'],fontsize=14) # setting ticks\n", "plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'],fontsize=14) # setting ticks\n", "\n", "plt.plot(x, f, color=\"blue\", linewidth=2.5, linestyle=\"-\", label=\"$\\sin(e^x)$\") # changing color and thickness\n", "plt.plot(x, g, color=\"red\", linewidth=2.5, linestyle=\"-\", label=\"$\\cos(2x)$\") # changing color and thickness\n", "plt.legend(loc='lower left',prop={'size':16}) # placing legend on bottom left\n", "plt.xlabel('$x$',fontsize=16) # horizontal axis name\n", "plt.ylabel('test functions',fontsize=16) # vertical axis name\n", "plt.title('Sample plot',fontsize=18) # title\n", "plt.grid(True) # enabling grid" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The image can be resized by dragging the handle in the lower right corner. Double clicking will return them to their original size.\n", "\n", "**One thing to be aware of is that by default, the *figure* object is cleared at the end of each cell.**\n", "\n", "You will need to issue all plotting commands for a single figure in a single cell.\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.savefig('trig_functions.pdf')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.savefig?" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Go on and open the *pdf* file. It is empty! Now uncomment the save line in the block where the figure is plotted." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3D-plotting\n", "\n", "The following example is adapted from [this tutorial](http://nbviewer.ipython.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-2-Numpy.ipynb). Let's define the following function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "alpha = 0.7\n", "phi_ext = 2*np.pi*0.5\n", "\n", "def flux_qubit_potential(phi_m, phi_p):\n", " return 2 + alpha - 2*np.cos(phi_p)*np.cos(phi_m) - alpha*np.cos(phi_ext - 2*phi_p)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now create a mesh and evaluate the function over that mesh:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "phi_m = np.linspace(0, 2*np.pi, 100)\n", "phi_p = np.linspace(0, 2*np.pi, 100)\n", "X,Y = np.meshgrid(phi_p, phi_m)\n", "Z = flux_qubit_potential(X, Y).T" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot the surface:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from mpl_toolkits.mplot3d.axes3d import Axes3D # imports 3D plotting\n", "from matplotlib import cm # module for color pattern\n", "fig = plt.figure(figsize=(14,6))\n", "\n", "# `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot\n", "ax = fig.add_subplot(1, 2, 1, projection='3d')\n", "\n", "p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)\n", "\n", "# surface_plot with color grading and color bar\n", "ax = fig.add_subplot(1, 2, 2, projection='3d')\n", "p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)\n", "cb = fig.colorbar(p, shrink=0.5) # enables colorbar" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Better control over plotting\n", "\n", "So far, we **`matplotlib.pyplot`** module directly to produce plots. Sometimes we need more control over the the plots position, axes, insets, etc. We might also need to create different figures, or add different axes, put insets, etc. The following commands demonstrate this functionality." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Let's generate some synthetic data\n", "data = np.random.uniform(size=(100,2))\n", "x, y = data[:,0], data[:,1]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Let's create a fugure objec and an axes object\n", "fig1 = plt.figure(figsize=(6,6))\n", "ax1 = fig.add_axes([0.10,0.20,0.78,0.40]) # left, bottom, width, height" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print dir(fig1)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print dir(plt)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Don't forget to create figures and axes in the cell you are plotting!\n", "fig = plt.figure(figsize=(6,6))\n", "ax1 = fig.add_axes([0.10,0.20,0.78,0.80]) # left, bottom, width, height\n", "\n", "# Ex: Specify a title and the axes labels\n", "\n", "ax1.scatter(x, y, marker='o')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Insets through multiple axes" ] }, { "cell_type": "code", "collapsed": false, "input": [ "fig = plt.figure()\n", "\n", "axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes\n", "axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes\n", "\n", "# main figure\n", "axes1.plot(x, y, 'r.')\n", "axes1.set_xlabel('x')\n", "axes1.set_ylabel('y')\n", "axes1.set_title('title')\n", "\n", "# insert\n", "axes2.plot(y, x, 'g.')\n", "axes2.set_xlabel('y')\n", "axes2.set_ylabel('x')\n", "\n", "# Ex: add a title to the inset with a font size of 12px\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What if you want to enlarge some region of the figure and show it in the inset? Let's how we can do that." ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = np.linspace(0,np.pi,1000)\n", "f = np.sin(8*np.exp(x))\n", "g = np.cos(2*x)\n", "\n", "# How to enlarge a region on a plot?\n", "fig = plt.figure(figsize=(8, 6))\n", "ax = fig.add_axes([0.15,0.11,0.83,0.83])\n", "ax.set_xlim([0, 5])\n", "ax.plot(x,f)\n", "ax.plot(x,g)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset\n", "zoomed_inset_axes?" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "fig = plt.figure(figsize=(8, 6))\n", "ax = fig.add_axes([0.15,0.11,0.83,0.83])\n", "ax.set_xlim([0, 5])\n", "ax.plot(x,f,linewidth=0.5)\n", "ax.plot(x,g)\n", "\n", "# The inset axes\n", "axins = zoomed_inset_axes(ax, 8, loc=1)\n", "axins.plot(x, f, linewidth=1)\n", "axins.plot(x, g, linewidth=2)\n", "axins.set_xlim([2.85, 3.0])\n", "axins.set_ylim([0.9, 1.0])\n", "\n", "# Mark inset\n", "mark_inset(ax, axins, loc1=3, loc2=2, fc=\"none\", ec=\"0\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**`Matplotlib`** is a very rich library, and it has the functionality for literrally any kind of plotting. For more refence, you can check out a very detailed [User Guide](http://matplotlib.org/users/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Beautiful and easy plot styling" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A recently developed [Seaborn](http://stanford.edu/~mwaskom/software/seaborn/tutorial.html) package provides many different options of how to control the plot aesthetics. Let's look at some examples." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# A very quick enhancement by just importing seaborn\n", "import seaborn as sns\n", "sns.set_style(\"whitegrid\")\n", "\n", "x = np.linspace(0,np.pi,1000)\n", "f = np.sin(np.exp(x))\n", "g = np.cos(2*x)\n", "plt.plot(x,f)\n", "plt.plot(x,g)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "sns.set_style?" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A few more examples:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Bar plots\n", "sns.set_style(\"whitegrid\")\n", "data = np.random.normal(size=(20, 6)) + np.arange(6) / 2\n", "sns.boxplot(data);" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Violing plots\n", "f, ax = plt.subplots()\n", "sns.violinplot(data)\n", "sns.despine(offset=10, trim=True);" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# What are the styles and how to override them?\n", "sns.axes_style()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Color paletes available in `seaborn`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "current_palette = sns.color_palette()\n", "sns.palplot(current_palette)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.plot([0, 1], [0, 1], sns.xkcd_rgb[\"pale red\"], lw=3)\n", "plt.plot([0, 1], [0, 2], sns.xkcd_rgb[\"medium green\"], lw=3)\n", "plt.plot([0, 1], [0, 3], sns.xkcd_rgb[\"denim blue\"], lw=3);" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References:\n", "\n", "- [Numpy for Matlab users](http://www.scipy.org/NumPy_for_Matlab_Users)\n", "- [Hans Petter Langtangen book](http://link.springer.com/book/10.1007/978-3-642-02475-7/page/1)\n", "\n", "\n", "#### Matplotlib\n", "\n", "- [Nicolas P. Rougier matplotlib tutorial](http://www.loria.fr/~rougier/teaching/matplotlib/)\n", "- [Pyplot tutorial](http://matplotlib.org/users/pyplot_tutorial.html)\n", "- [Matplotlib gallery](http://matplotlib.org/gallery.html)\n", "\n", "#### Other visualization packages\n", "- [Seaborn styling package tutorial](http://stanford.edu/~mwaskom/software/seaborn/tutorial.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Copyright 2015, Maruan Al-Shedivat, Yiannis Hadjimichael, ACM Student Chapter.*" ] } ], "metadata": {} } ] }