{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Data Analysis with Jupyter Notebooks.\n", "\n", "# Tutorial 4\n", "\n", "Benjamin J. Morgan, University of Bath." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Contents\n", "\n", "- [Plotting data with matplotlib](#matplotlib)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Plotting data with matplotlib\n", "\n", "To plot data we use another module: [`matplotlib`](http://matplotlib.org) This is a very powerful (and complicated) plotting library, that be used for quick analysis of experimental data, or to generate publication quality figures. It supports an enormous number of plot types. We are going to start with simple 2D $x,y$ plots.\n", "\n", ">```python\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline\n", "import numpy as np\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `import` statement loads up the part of the `matplotlib` library we will use for plotting, and lets us refer to this as `plt` for convenience later.\n", "\n", "The `%matplotlib inline` command tells the Jupyter notebook that we want all out “plots” to appear “inline”, i.e. inside the notebook (alternatives include opening the plots in other windows, or saving them as graphics files). The `%` symbol at the start means this is a “magic” command for controlling the behaviour of this Jupyter notebook, and is not standard Python.\n", "\n", "If you are using a high resolution screen, you will also want to switch on high resolution figures.\n", "\n", ">```python\n", "%config InlineBackend.figure_format = 'retina'\n", "```\n", "\n", "We also import `numpy` as `np` so that we can store our data as arrays." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Creating a plot uses `plt.plot()`. Remember, we have assigned `plt` as shorthand for `matplotlib.pyplot`.\n", "\n", ">```python\n", "# plot the numpy arrays a and b against each other\n", "import numpy as np\n", "a = np.array( [ 1, 2, 3, 4 ] )\n", "b = np.array( [ 5, 6, 7, 8 ] )\n", "print( \"a:\", a )\n", "print( \"b:\", b )\n", "plt.plot( a, b )\n", "plt.show()\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This can be used for plotting $y$ as a function of $x$, e.g. $y=x^2$.\n", "\n", ">```python\n", "x = np.array( [0, 1, 2, 3, 4, 5] )\n", "y = x**2\n", "plt.plot( x, y )\n", "plt.show()\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "