# CS 101 Lab: Week # 15 (Introduction to scientific plotting) <ul class="pager"> <li><a href="../w14/">← Previous lab</a></li> <li><a href="../w16/">Next lab →</a></li> </ul> It is planned to cover the following during the 15th week of CS101 labs. This lab will be an introduction to scientific plotting, based on what have been seen in lectures during the last 2 weeks (April 2015). --- ## Assignment for today and next week lab ### Exercise 1: simple plots 1. Create a new program (in Spyder), and import the two modules `numpy` as `np` and `matplotlib.pyplot` as `plt` (usual conventions, as explained in lectures). 2. Draw your first plot footnote{ Cf. http://www.labri.fr/perso/nrougier/teaching/matplotlib/#simple-plot}: $y = \\sin(x)$ for $x \\in [-\\pi, \\pi]$. Do the same for $\\cos$: on a new plot (on a new figure, that can be opened with the command `plt.figure()`), or on the same plot but with a different colour (call twice the `plt.plot()` function). 3. Choose some polynomials that you like (of different degrees), then defines them as functions in Python (like `def f1(x): return x**4 + x**3 - 2*x + 1`). Define at least 6 polynomials like this, then create a new figure, and plot these polynomial functionals. 4. For the previous plot, add an appropriate title (with the `plt.title()` function). Then add a legend footnote{ This has also been seen in lectures, but please find here a small explanatory paragraph.}, which should show the function associated with each of the colors (one the plot, each line have a color, the legend have to show the math formula that was used to draw that line: $x^4 + x^3 - 2x + 1$). The `plt.legend()` function can be used in two ways: either you give it a list of labels (Python strings), like `plt.legend(["f1", "f2"])`, or by just calling it like `plt.legend()`. The second approach needs that each previous `plt.plot()` calls used a `label` argument. For example, something like `plt.plot(X, Y1, label="Function 1")`, then `plt.plot(X, Y2, label="Function 2")`, then `plt.legend()` will plot the data $(X, Y1)$ and $(X, Y2)$, with a label "Function 1" associated with $Y1$ and "Function 2" associated with $Y2$. ### Exercise 2: Plotting the successive Taylor expansion of a function 1. For a function $f$, of class $\mathcal{C}^n$ at a point $x\_0$ (for $n \\geq 0$), we write $T\_n(f, x\_0)(x)$ the Taylor expansion for $f$ at the point $x\_0$ and order $n$ (as a function of $x$). Mathematically, we recall that $T\_n(f, x\_0)(x)$ is defined as $\\sum\_{k = 0}^{n} f^{(k)}(x\_0) \\frac{(x - x\_0)^k}{k!}$. 2. This exercise is focused on the function exponential ($f = \\exp : x\\mapsto \\exp(x)$). On your paper, write the expression of the first $5$ Taylor expansion $T\_0$, $T\_1$, $T\_2$, $T\_3$, $T\_4$. 3. On a MatPlotLib plot, start by plotting the exponential function, then its successive Taylor expansion. Be careful about the $x$ domain that you chose to show (default settings can be modified with the `plt.xlim` function, taking a tuple of the form $(xmin, xmax)$). 4. As previously, add a title and a useful legend. You can add a label to the $x$-axis with the `plt.xlabel` function, and the $y$-axis label with `plt.ylabel` function (both accept one string argument, like `plt.xlabel("x")` and `plt.ylabel("Age of the captain")`). ### Exercise 3: Customize the previous plot 1. Similarly, the functions `plt.xticks` or `plt.yticks` can be used to change the ticks that are attached to $x$ and $y$ axes. 2. Now, try to change the size of the lines by giving a `linewidth` number as a keyword argument to the `plt.plot()` function (e.g. `plt.plot(X, Y, linewidth=3.5)`). 3. The style and color of the lines can also be changed, by giving strings with the `linestyle` and `color` arguments, like `plt.plot(X, Y, color='red')` or `plt.plot(X, Y, linestyle='*')`. 4. When you are happy of how your plot looks like, save it! Use the function `plt.savefig()`, like this for example: `plt.savefig("my_first_plot.png")` (for a PNG image named `"my_first_plot.png"`). Try different file formats, by changing the extension of the file: PNG (`.png`, a lossless compressed format for colored images), PDF (`.pdf`, Portable Document Format, a compressed format for numerical document with text and images), JPEG (`.jpg`, compressed images), SVG (`.svg`, standard format for vector graphics, mostly used for the Web) etc. ### Exercise 4: Artificial data 1. As seen previously, generate some random data, either by using `random.uniform` and a for loop, or the NumPy random module `np.random` (check its doc for more information). You will chose a number of points, like `N = 200`, and then generate random values for $x$ and $y$ coordinates, and store them in two lists (or NumPy array, created with the `np.array` function). 2. Then, plot these points, first with the `plt.plot()` function (be sure to not link them, it would be confuse, so choose a `linestyle` that is a discrete one, like `+` for $+$, `*` for $*$, `o` for $o$ etc). 3. Then use the `plt.scatter()` function. Which one look nicer? This `plt.scatter` function accepts one argument `color`, than accepts either one simple color (like "red" or "blue"), or a list (or array) of colors. You can also give a list of numerical values, that will be used as an index on a certain color scale. Long story short, define an third array `c` that will be the polar angle of each points $(x\_i, y\_i)$: `c = np.arctan2(Y, X)`. Observe the change on the plot (`plt.scatter(X, Y, color=c)`). ### Exercise 5: Other kinds of plots (next week) By using the same function `plt.plot`, draw different kinds of plots: 1. A sequence ($(n, u\_n)$ for the starting values $0 \\leq n \\leq N$). Chose a sequence that you like (or a really simple one, from MA101), and a not-too-big value for $N$. Examples: $u\_n = (-1)^n$, $u\_n = \\sin(n)$ etc. 2. A parametric curve $(x(t), y(t))$ for $t \\in I$ a certain interval. Similarly, chose a parametric curve from MA102, or a simple example. E.g. $(x(t), y(t)) = (t - \\sin(t), 1 - \\cos(t))$, $(x(t), y(t)) = (\\cos^3(t), \\sin^3(t))$ etc. 3. A polar curve $r(\\theta)$. First, chose an easy case (like $r(\\theta) = \\cos(\\theta)$), an interval of values for $\\theta$, a number of values $n$; and then try two approaches to draw its curve. Either you compute manually the $(x, y)$ coordinates ($x = \\cos(\\theta) r(\\theta)$, $y = \\sin(\\theta) r(\\theta)$), and use the `plt.plot` function; or directly use the `plt.polar` function that does this automatically. ### Exercise 6: Different kind of 3D plots 1. First, import the `Axes3D` module with `from mpl_toolkits.mplot3d import Axes3D`. Then, define an object `ax` with `ax = plt.axes(projection='3d')`. This will tell MatPlotLib to show a 3D plot. 2. As previously, generate some data in three lists (or array) `X, Y, Z`. For example, `X = Y = np.linspace(-4, 4, 400)`, and `Z = X**2 + Y**2` are points on a paraboloid. You can use the `ax.plot` or `ax.scatter` methods with three arrays instead of two, like `plt.plot(X, Y, Z)`. 3. Create a new `ax` object, then experiment with the `ax.plot\_surface` function (which also accepts three arrays `X, Y, Z`. By default it will be colored in shades of a solid color. 4. Try also the methods `ax.contour()`, `ax.contourf()` or `ax.clabel()` to draw a 2D representation of the contours of a surface (`ax.contour()` and `ax.contourf()` draw contour lines and filled contours, respectively, and `ax.clabel()` write labels on the contour lines). 5. (*bonus*) If you have time, also try the `ax.plot\_trisurf()` method to draw a 3D surface with a Triangulation, or the `ax.plot_wireframe()` method to draw a 3D wireframe. > See [http://matplotlib.org/devdocs/mpl_toolkits/mplot3d/tutorial.html](http://matplotlib.org/devdocs/mpl_toolkits/mplot3d/tutorial.html) for a more advanced tutorial. ### Exercise 7: Statistical plots for random data 1. You did it during one lab already, do it again: generate a list of 231 grades, float numbers with one digit after the comma, uniformly taken between $0$ and $100$. 2. Then, explore by yourself the `plt.pie()` and `plt.bar()` functions, that respectively draws a pie chart and a bar plot. 3. By using a list and a for loop (or a good list comprehension), compute how many students got their grade between $0$ and $30$ percent (they will fail), how many between $30$ and $70$ and how many above $70%$ (you can also chose the intervals that you think are interested). 4. Then plot this either in a pie chart and a bar plot. It should look like what we have showed you for the two Mid-Term Exams. Add some labels to your pie chart, and a good legend to your bar plots. > See [the example on Moodle](https://bitbucket.org/lbesson/python-demos/src/master/Histogram_plotting_CS101_grades__Second_Mid_Term_2015.py) (online [https://bitbucket.org/lbesson/python-demos/src/master/Histogram_plotting_CS101_grades__Second_Mid_Term_2015.py](https://bitbucket.org/lbesson/python-demos/src/master/Histogram_plotting_CS101_grades__Second_Mid_Term_2015.py)). The source code program is already given in moodle. --- <div class="alert"> <h3>This outline might change</h3> <p>This outline for the lab #15 is a preliminary version, it might change.<br> If needed, please <a href="https://bitbucket.org/lbesson/cs_101/issues/new" title="It's free, open to anyone, quick and easy!">fill a bug report</a>?</p> </div> --- <ul class="pager"> <li class="previous"><a href="../w14/">← Previous lab</a></li> <li class="next"><a href="../w16/">Next lab →</a></li> </ul>