{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lecture 5: Matplotlib\n", "\n", "Today, we will learn \n", "* More advanced slicing technique on arrays.\n", "* how to use matplotlib's `pyplot` submodule to draw the graph of a function. `pyplot` is a collection of command style functions that make matplotlib work like MATLAB. Each `pyplot` function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.\n", "\n", "Using `pyplot` is also a first example of the application of vectorization.\n", "\n", "Reference:\n", "[Pyplot tutorial](https://matplotlib.org/tutorials/introductory/pyplot.html)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr = np.arange(12)+1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[:3]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[3:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr = arr.reshape(3,-1)\n", "print(arr)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[1:,:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arr[:,0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dir(arr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## More advanced tricks" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X = np.array(range(20)).reshape((4,-1))\n", "print(X)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X[:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X[1:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X[1::]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X[::-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X[::2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X[0:2,1:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setting Values with Slicing" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X[:,1] = np.zeros(4)\n", "print(X)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X[0:2,1:] += 10\n", "print(X)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### In-class exercise 1\n", "Make the following 5 by 5 array, without using `FOR` or `WHILE` loops:\n", "```python\n", "array([[0, 0, 0, 0, 0],\n", " [0, 1, 2, 3, 0],\n", " [0, 4, 5, 6, 0],\n", " [0, 7, 8, 9, 0],\n", " [0, 0, 0, 0, 0]])\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matplotlib" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import math\n", "from math import pi # so that we can use pi directly instead of math.pi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Say if we want to plot $y = \\cos(x)$ and $y = \\sin(x)$, first we produce a bunch of equi-distant points using `linspace` function in `numpy`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xs = np.linspace(0, 2*pi, 200)\n", "# it generates an array of 200 points between 0 and 2*pi\n", "cosxs = np.cos(xs) # evaluates cos at these 200 points\n", "sinxs = np.sin(xs)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Vectorization remark: this cos is from math module\n", "# it cannot be directly applied to xs\n", "math.cos(xs)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# plt is the pyplot function in the matplotlib module\n", "# to connect the all the dots\n", "# %matplotlib qt\n", "plt.plot(xs, cosxs) # first one is blue\n", "plt.plot(xs, sinxs) # second one is orange" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# optional\n", "# we could even annotate the graph we have\n", "plt.plot(xs, cosxs, color = 'blue') \n", "plt.plot(xs, sinxs, color = 'red') \n", "plt.grid(True)\n", "plt.axis('auto')\n", "plt.annotate('local maximum of $sin(x)$', xy=(pi/2, 1), xytext=(3, 1.5), \n", " arrowprops = dict(facecolor='black',shrink = 0.1))\n", "plt.show() # suppress the output, similar to `drawnow` in MATLAB" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## In-class exercise\n", "\n", "Estimate $\\pi$ by adding the first $100$ terms in the formula: \n", "$$\\frac{\\pi}{4} = 1 - \\frac13 + \\frac15 - \\frac17+ \\cdots,$$ \n", "which comes from the Taylor expansion of $\\arctan(x)$.\n", "\n", "Compare the answer to the built-in `math.pi` (you want to import `math` module) by the following:\n", "* Creating a numpy array `estpi` to store the first $100$ approximation along the way. For example, `estpi[0]` should be $4\\cdot 1$, `estpi[1]` should be $4\\cdot \\left(1 - \\frac13\\right)$, `estpi[2]` should be $4\\cdot \\left(1 - \\frac13 + \\frac15\\right)$, etc.\n", "* Create another index array of shape `(100,)` to represent the indices, you can use `linspace` or `arange`.\n", "* Create a numpy array `actpi` to store the actual $\\pi$ value that has the same shape with `estpi`.\n", "* Use `plt` in `pyplot` to plot `estpi` and `actpi` against the index array. Suggestion: use different `color`, `linewidth`, `linestyle`.\n", "\n", "Reference: [matplotlib.pyplot.plot](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html)" ] } ], "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.2" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": true, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }