{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Tutorial 01 - Introduction to Python and Jupyter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Basic concepts and features of Python, numeric and math-related functions and data types, Jupyter environment, numpy, scipy, matplotlib modules." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jupyter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "From the official website [jupyter.org](https://jupyter.org): \n", "\n", "> The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Keyboard shortcuts of the most frequent commands:\n", "\n", "- create cell above / below selected: A / B
\n", "- delete selected cell: D + D
\n", "- change cell to markdown: M
\n", "- change cell to code: Y
\n", "- execute cell: Ctrl + Enter (or Shift + Enter)\n", "- show keyboard shortcuts: H
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- high-level, object-oriented, general purpose programming language\n", "- open source (free to use and distribute, including for commercial purposes)\n", "- interpreted (no need to compile the code)\n", "- simple-to-learn syntax and excellent readability\n", "- large community\n", "- numerous libraries for scientific computing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variable assignment and basic operations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "assign number $ 4 $ to variable $ x $ and print the value of $ x $:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "x = 4\n", "print(x) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the type of variable $ x $ using the [`type`](https://docs.python.org/3/library/functions.html#type) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "single-line comments:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# this is a single-line comment" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "multi-line comments:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", "this is \n", "a multi-line\n", "comment\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "assign number $ 2 $ to variable $ a $, assign number $ 4 $ to variable $ b $, and print sum, difference, product, and quotient of both variables:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "a = 2\n", "b = 4 \n", "print(a + b, a - b, a * b, a / b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "assign number $ 2 $ to variable $ c $ and print square-root of $ c $ and $ c $ to the power of $ 2 $ using the `**` operator:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "c = 2 \n", "print(c**0.5, c**2) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a list $ l $ of $ 1 $, $ 2.0 $, $ 3 $, and $ c $ (lists can contain any type of variable) and print the content of $ l $:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "l = [1, 2.0, 3, \"c\"]\n", "print(l) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conditions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "check if $ x $ is equal to $ 4 $, check if $ x $ is not equal to $ 3 $ using the operators `==` and `!=`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(x == 4, x != 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "check if $ x $ is greater than $ 1 $ and less than $ 3 $, check if $ x $ is equal to $ 3 $ or $ 4 $ using the operators `and` and `or`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(x > 1 and x < 3, x == 3 or x == 4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "if the value of variable $ x $ is less than or equal to $ 3 $, print \"x <= 3\", if the value of variable $ x $ is greater than $ 3 $ and less than $ 5 $, print \"3 < x < 5\", else print \"x >= 5\" using the [`if`](https://docs.python.org/3/reference/compound_stmts.html#if), [`elif`](https://docs.python.org/3/reference/compound_stmts.html#elif), and [`else`](https://docs.python.org/3/reference/compound_stmts.html#else) statements (note that in Python the code blocks must be indented - both tabs and spaces are supported):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if x <= 3:\n", " print(\"x <= 3\") \n", "elif x > 3 and x < 5: \n", " print(\"3 < x < 5\")\n", "else: \n", " print(\"x >= 5\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "use the `in` operator to check if the list $ l $ contains character $ c $:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"c\" in l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "use the `in` and `not` operators to check if the number 4 is not in the list $ l $:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(4 not in l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the sequence of numbers from 0 to 2 using the [`range`](https://docs.python.org/3/library/stdtypes.html#range) function and [`for`](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement) loop (note that the [`range`](https://docs.python.org/3/library/stdtypes.html#range) function is zero based):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "for i in range(3):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the sequence of numbers from $ 3 $ to $ 5 $:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(3, 6):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "iterate over a sequence given by list:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for x in [1,5,4]:\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[`while`](https://docs.python.org/3/reference/compound_stmts.html#while) loops repeat as long as a certain boolean condition is met (note that the [`else`](https://docs.python.org/3/reference/compound_stmts.html#else) clause can be used in loops):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "k = 10\n", "while k > 5:\n", " print(\"k =\", k)\n", " k = k - 1 # or k -= 1\n", "else:\n", " print(\"k <= 5\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "define a function that takes two numbers and returns their product using the `def` keyword:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def multiply(x, y):\n", " return x*y\n", "\n", "print(multiply(2, 3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "generate an exception using the [`raise`](https://docs.python.org/3/reference/simple_stmts.html#raise) statement (exceptions are used to abort functions when some error condition occurs):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "raise Exception(\"description of the error\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "use the [`try`](https://docs.python.org/3/reference/compound_stmts.html#try) and [`except`](https://docs.python.org/3/reference/compound_stmts.html#except) statements to catch the error thrown by `multiply` function when multiplying two strings:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " multiply(\"a\", \"b\")\n", "except Exception as e:\n", " print(\"Caught an exception: \" + str(e))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "redefine the `multiply` function using the `lambda` keyword:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "z = lambda x, y: x*y\n", "\n", "z(2, 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Further reading: https://docs.python.org/3/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numpy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "import the [`numpy`](https://numpy.org/) module and bind the import to the local variable `np` (to avoid name collisions and shorten module name):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print $ \\sqrt{4} $, $ \\left|-1 \\right| $, $ \\exp{(1)} $, $ \\ln{(e)} $, $ \\sin{(\\pi)}$, and $ \\cos{(\\pi)} $ using the functions from [`numpy`](https://numpy.org/) module:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(np.sqrt(4), np.abs(-1), np.exp(1), np.log(np.e), np.sin(np.pi), np.cos(np.pi))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a vector $ v $ of numbers from $ 1 $ to $ 9 $ using the [`array`](https://numpy.org/doc/stable/reference/generated/numpy.array.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])\n", "print(v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a $ 3 \\times 3 $ matrix $ \\mathbb{M} $ of numbers from $ 1 $ to $ 9 $ using the [`array`](https://numpy.org/doc/stable/reference/generated/numpy.array.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n", "print(M)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the dimensions of the vector $ v $ and matrix $ \\mathbb{M} $ using the [`shape`](https://numpy.org/doc/stable/reference/generated/numpy.shape.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(np.shape(v), np.shape(M))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print number of elements of the vector $ v $ and matrix $ \\mathbb{M} $ using the [`size`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.size.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "print(np.size(v), np.size(M))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the scalar product $ v \\cdot v $ using the [`dot`](https://numpy.org/doc/stable/reference/generated/numpy.dot.html) function (compare with the element-wise multiplication using the operator `*`):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(np.dot(v, v)) # alternatively v @ v\n", "print(v * v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the matrix product $ \\mathbb{M} \\cdot \\mathbb{M} $ using the [`dot`](https://numpy.org/doc/stable/reference/generated/numpy.dot.html) function (compare with the element-wise multiplication using the operator `*`):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "print(np.dot(M, M)) # alternatively M @ M\n", "print(M * M)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the first, last, and the sixth element of vector $ v $:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "print(v[0], v[-1], v[5])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the first five, last four, and each second element of vector $ v $ using the numpy array [indexing](https://numpy.org/doc/stable/reference/arrays.indexing.html):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(v[:5], v[5:], v[::2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print the $ \\mathbb{M}_{0, 0} $ element, the first row, and the second column of matrix $ \\mathbb{M} $:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "print(M[0, 0], M[0, :], M[:, 1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create evenly spaced vector $ x $ of size $ 5 $ from $ -2 $ to $ 2 $ using the [`linspace`](https://numpy.org/doc/stable/reference/generated/numpy.linspace.html) function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.linspace(-2, 2, 5)\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create evenly spaced vector $ x $ of size $ 5 $ from $ -2 $ to $ 2 $ using the [`linspace`](https://numpy.org/doc/stable/reference/generated/numpy.linspace.html) function and print the step size:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x, h = np.linspace(-2, 2, 5, retstep=True)\n", "print(h)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create evenly spaced vector $ x $ from $ -2 $ to $ 2 $ with a step of size $ 1 $ using the [`arange`](https://numpy.org/doc/stable/reference/generated/numpy.arange.html) function: " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.arange(-2, 2, 1.0)\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a matrix from the vector $ x $ using the [`meshgrid`](https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xx, yy = np.meshgrid(x, x)\n", "print(xx[1,0], yy[1, 0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a vector of zeros of size $ 3 $ using the [`zeros`](https://numpy.org/doc/stable/reference/generated/numpy.zeros.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "z = np.zeros(3)\n", "print(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a $ 3 \\times 3$ matrix of zeros using the [`zeros`](https://numpy.org/doc/stable/reference/generated/numpy.zeros.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "Z = np.zeros((3, 3))\n", "print(Z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a $ 3 \\times 3 $ matrix with ones on the diagonal and zeros elsewhere using the [`eye`](https://numpy.org/doc/stable/reference/generated/numpy.eye.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "D = np.eye(3)\n", "print(D)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a $ 3 \\times 3 $ matrix filled with ones using the [`ones`](https://numpy.org/doc/stable/reference/generated/numpy.ones.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "O = np.ones((3, 3))\n", "print(O)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a $ 3 \\times 3 $ matrix filled with random floating point numbers between $ 0 $ and $ 1 $ using the [`rand`](https://numpy.org/doc/stable/reference/random/generated/numpy.random.rand.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "R = np.random.rand(3, 3)\n", "print(R)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a $ 3 \\times 3 $ matrix with the vector $ (1, 2, 3) $ on the diagonal using the [`diag`](https://numpy.org/doc/stable/reference/generated/numpy.diag.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "print(np.diag([1,2,3], 0))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "extract the main diagonal, and the diagonals above and below the main diagonal from matrix $ \\mathbb{M} $ using the [`diag`](https://numpy.org/doc/stable/reference/generated/numpy.diag.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(np.diag(M, 0), np.diag(M, 1), np.diag(M, -1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "set all elements of matrix $ \\mathbb{M} $ below and above diagonal to zero using the [`triu`](https://numpy.org/doc/stable/reference/generated/numpy.triu.html) and [`tril`](https://numpy.org/doc/stable/reference/generated/numpy.tril.html) functions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(np.triu(M))\n", "print(np.tril(M))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print minimum and maximum elements, index of minimum and maximum elements, and the sum of vector $ v $ using the [`min`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.html), [`max`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.max.html), [`argmin`](https://numpy.org/doc/stable/reference/generated/numpy.argmin.html), [`argmax`](https://numpy.org/doc/stable/reference/generated/numpy.argmax.html), and [`sum`](https://numpy.org/doc/stable/reference/generated/numpy.sum.html) functions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(np.min(v), np.max(v), np.argmin(v), np.argmax(v), np.sum(v))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print even numbers of vector $ v $ and their indices using the [`where`](https://numpy.org/doc/stable/reference/generated/numpy.where.html), [`argwhere`](https://numpy.org/doc/stable/reference/generated/numpy.argwhere.html), and [`mod`](https://numpy.org/doc/stable/reference/generated/numpy.mod.html) functions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "even = np.where(np.mod(v, 2) == 0)\n", "print(v[even])\n", "\n", "indices = np.argwhere(np.mod(v, 2) == 0)\n", "print(v[indices])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "assign vector $ v $ to vector $ v_2 $ using the `=` operator (note that if you modify one in place, you'll see the change through the other one too):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "v2 = v\n", "v2[0] = -1\n", "print(v)\n", "print(v2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "copy the vector $ v $ to vector $ v_3 $ using the [`copy`](https://numpy.org/doc/stable/reference/generated/numpy.copy.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "v3 = np.copy(v)\n", "v3[0] = -2\n", "print(v)\n", "print(v3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create vector $ v_4 $ by appending $ 0 $ to the end of vector $ v $ using the [`append`](https://numpy.org/doc/stable/reference/generated/numpy.append.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "v4 = np.append(v, 0)\n", "print(v4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create vector $ v_5 $ by inserting $ -5 $ as a sixth element to vector $ v $ using the [`insert`](https://numpy.org/doc/stable/reference/generated/numpy.insert.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "v5 = np.insert(v, 5, -5)\n", "print(v5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create vector $ v_6 $ by concatenating vectors $ v_4 $ and $ v_5 $ using the [`concatenate`](https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "v6 = np.concatenate((v4, v5))\n", "print(v6)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create polynomial $ p = x^3 + 2x^2 + 3x + 2 $ using the [`poly1d`](https://numpy.org/doc/stable/reference/generated/numpy.poly1d.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "p = np.poly1d([1, 2, 3, 2])\n", "print(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Further reading: https://numpy.org/doc/stable/reference/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Scipy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "import scientific constants from the [`scipy`](https://www.scipy.org/) module and print $ \\pi $, golden_ratio, and speed of light in vacuum:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from scipy.constants import pi, golden_ratio, c\n", "print(pi, golden_ratio, c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "import various submodules from [`scipy`](https://www.scipy.org/) that will be useful throughout the course: " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import scipy.linalg # linear algebra\n", "import scipy.interpolate # interpolation and curve fitting\n", "import scipy.optimize # minima, maxima, root finding\n", "import scipy.integrate # numerical integration and solving of ODEs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Further reading: https://docs.scipy.org/doc/scipy/reference/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matplotlib" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "import [`pyplot`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html) submodule from [`matplotlib`](https://matplotlib.org/) and bind the import to the local variable `plt`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use the command below to show the plots inside the Jupyter notebook (starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of IPython’s specific commands):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "plot $ \\sin{(x)} $ and $ \\cos{(x)} $ functions for $ x \\in [0, 10] $ using the [`plot`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.linspace(0, 10, 100)\n", "\n", "fig, ax = plt.subplots()\n", "ax.plot(x, np.sin(x))\n", "ax.plot(x, np.cos(x))\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "change the linestyles, axes labels, and add legend to the plot above:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "ax.plot(x, np.sin(x), linestyle=\"--\", color=\"red\", label=\"y = sin(x)\", linewidth=2)\n", "ax.plot(x, np.cos(x), linestyle=\"-\", color=\"blue\", label=\"z = cos(x)\", linewidth=1)\n", "ax.set_xlabel(\"x\")\n", "ax.set_ylabel(\"y (x)\")\n", "ax.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "plot the functions $ y(x) = x $ and $ y(x) = x^2 $ for $ x \\in [0, 10] $ and show the plots next to each other:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "fig, ax = plt.subplots(nrows=1, ncols=2)\n", "\n", "ax[0].plot(x, x, color=\"green\")\n", "ax[0].set_xlabel(\"x\")\n", "ax[0].set_ylabel(\"y\")\n", "\n", "ax[1].plot(x, x**2, color=\"blue\")\n", "ax[1].set_xlabel(\"x\")\n", "ax[1].set_ylabel(\"y\")\n", " \n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "change the size of the figure using the `figsize` parameter:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(8,3))\n", "\n", "ax.plot(x, x, color=\"red\")\n", "ax.set_xlabel(\"x\")\n", "ax.set_ylabel(\"y\")\n", "ax.set_title(\"title\");\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "save the figure above as \"figure.png\":" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig.savefig(\"figure.png\", dpi=100)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a 2D plot of Gaussian function, $ f(x, y) = \\exp{(-x^2 - y^2)} $, for $ x, y \\in [-2, 2] $ using the [`pcolormesh`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pcolormesh.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "x = np.linspace(-2, 2, 100)\n", "y = np.linspace(-2, 2, 100)\n", "xx, yy = np.meshgrid(x, y)\n", "function = np.exp(-xx**2 - yy**2)\n", "\n", "fig, ax = plt.subplots()\n", "img = ax.pcolormesh(x, y, function, cmap=\"jet\", shading=\"gouraud\")\n", "ax.set_title(\"2D plot of Gaussian function\")\n", "ax.set_xlabel(\"x\")\n", "ax.set_ylabel(\"y\")\n", "\n", "cbar = plt.colorbar(img)\n", "cbar.set_label(label=r\"$ exp(-x^2 - y^2) $\", fontsize=12)\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a contour plot of function $ f(x, y) = x^2 - 2 \\sin(x + y) $ using the [`contour`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contour.html) function and draw a mark at the coordinates $ (0, \\ \\pi \\, / \\, 2) $ using the [`scatter`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html) function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "function_2 = xx**2 - 2.0 * np.sin(xx + yy) \n", "\n", "fig, ax = plt.subplots(figsize=(4, 4))\n", "contours = ax.contour(x, y, function_2, linestyles=\"--\", colors=\"blue\")\n", "ax.scatter(0, np.pi / 2, marker=\"+\", s=200, color=\"red\")\n", "ax.clabel(contours)\n", "ax.set_title(\"contour plot\")\n", "ax.set_xlabel(\"x\")\n", "ax.set_ylabel(\"y\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Further reading: https://matplotlib.org/" ] } ], "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.8.5" } }, "nbformat": 4, "nbformat_minor": 2 }