Commit 15a3e6cf authored by Mathieu Istas's avatar Mathieu Istas
Browse files

added figure for fibonnacci

parent 3aee1319
Pipeline #78849 passed with stage
in 1 minute and 9 seconds
%% Cell type:markdown id: tags:
 
# Python training UGA 2017
 
**A training to acquire strong basis in Python to use it efficiently**
 
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Oliver Henriot (GRICAD), Christophe Picard (LJK), Loïc Huder (ISTerre)
 
# Python scientific ecosystem
# A short introduction to Matplotlib ([gallery](http://matplotlib.org/gallery.html))
 
%% Cell type:markdown id: tags:
 
The default library to plot data is `Matplotlib`.
It allows one the creation of graphs that are ready for publications with the same functionality than Matlab.
 
%% Cell type:code id: tags:
 
``` python
# these ipython commands load special backend for notebooks
# (do not use "notebook" outside jupyter)
# %matplotlib notebook
# for jupyter-lab:
# %matplotlib ipympl
%matplotlib inline
```
 
%% Cell type:markdown id: tags:
 
When running code using matplotlib, it is highly recommended to start ipython with the option `--matplotlib` (or to use the magic ipython command `%matplotlib`).
 
%% Cell type:code id: tags:
 
``` python
import numpy as np
import matplotlib.pyplot as plt
```
 
%% Cell type:code id: tags:
 
``` python
A = np.random.random([5,5])
```
 
%% Cell type:markdown id: tags:
 
You can plot any kind of numerical data.
 
%% Cell type:code id: tags:
 
``` python
lines = plt.plot(A)
```
 
%% Output
 
 
%% Cell type:markdown id: tags:
 
In scripts, the `plt.show` method needs to be invoked at the end of the script.
 
%% Cell type:markdown id: tags:
 
We can plot data by giving specific coordinates.
 
%% Cell type:code id: tags:
 
``` python
x = np.linspace(0, 2, 20)
y = x**2
```
 
%% Cell type:code id: tags:
 
``` python
plt.figure()
plt.plot(x,y, label='Square function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
```
 
%% Output
 
<matplotlib.legend.Legend at 0x7f39e3136d68>
 
 
%% Cell type:markdown id: tags:
 
We can associate the plot with an object figure. This object will allow us to add labels, subplot, modify the axis or save it as an image.
 
%% Cell type:code id: tags:
 
``` python
fig = plt.figure()
ax = fig.add_subplot(111)
res = ax.plot(x, y, color="red", linestyle='dashed', linewidth=3, marker='o',
markerfacecolor='blue', markersize=5)
 
ax.set_xlabel('$Re$')
ax.set_ylabel('$\Pi / \epsilon$')
```
 
%% Output
 
Text(0, 0.5, '$\\Pi / \\epsilon$')
 
 
%% Cell type:markdown id: tags:
 
We can also recover the plotted matplotlib object to get info on it.
 
%% Cell type:code id: tags:
 
``` python
line_object = res[0]
print(type(line_object))
print('Color of the line is', line_object.get_color())
print('X data of the plot:', line_object.get_xdata())
```
 
%% Output
 
<class 'matplotlib.lines.Line2D'>
Color of the line is red
X data of the plot: [0. 0.10526316 0.21052632 0.31578947 0.42105263 0.52631579
0.63157895 0.73684211 0.84210526 0.94736842 1.05263158 1.15789474
1.26315789 1.36842105 1.47368421 1.57894737 1.68421053 1.78947368
1.89473684 2. ]
 
%% Cell type:markdown id: tags:
 
### Example of multiple subplots
 
%% Cell type:code id: tags:
 
``` python
fig = plt.figure()
ax1 = fig.add_subplot(211) # First, number of subplots along X (2), then along Y (1), then the id of the subplot (1)
ax2 = fig.add_subplot(212, sharex=ax1) # It is possible to share axes between subplots
X = np.arange(0, 2*np.pi, 0.1)
ax1.plot(X, np.cos(2*X), color="red")
ax2.plot(X, np.sin(2*X), color="magenta")
ax2.set_xlabel('Angle (rad)')
```
 
%% Output
 
Text(0.5, 0, 'Angle (rad)')
 
 
%% Cell type:markdown id: tags:
 
## Anatomy of a Matplotlib figure
 
![Anatomy of a figure](fig/anatomy.png)
 
For consistent figure changes, define your own stylesheets that are basically a list of parameters to tune the aspect of the figure elements.
See https://matplotlib.org/tutorials/introductory/customizing.html for more info.
 
%% Cell type:markdown id: tags:
 
We can also plot 2D data arrays.
 
%% Cell type:code id: tags:
 
``` python
noise = np.random.random((256,256))
plt.figure()
plt.imshow(noise)
```
 
%% Output
 
<matplotlib.image.AxesImage at 0x7f39e2ef9438>
 
 
%% Cell type:markdown id: tags:
 
We can also add a colorbar and adjust the colormap.
 
%% Cell type:code id: tags:
 
``` python
plt.figure()
plt.imshow(noise, cmap=plt.cm.gray)
plt.colorbar()
```
 
%% Output
 
<matplotlib.colorbar.Colorbar at 0x7f39e167e780>
 
 
%% Cell type:markdown id: tags:
 
#### Choose your colormaps wisely !
When doing such colorplots, it is easy to lose the interesting features by setting a colormap that is not adapted to the data.
 
Also, when producing scientific figures, think about how will your plot will look like to colorblind people or in greyscales (as it can happen in printed articles...).
 
See the interesting discussion on matplotlib website: https://matplotlib.org/users/colormaps.html.
 
%% Cell type:markdown id: tags:
 
## Other plot types
Matplotlib also allows to plot:
- Histograms
- Plots with error bars
- Box plots
- Contours
- in 3D
- ...
 
See the [gallery](http://matplotlib.org/gallery.html) to see what suits you the most.
 
%% Cell type:markdown id: tags:
 
## Do it yourself:
 
With miscellaneous routines of scipy we can get an example image:
 
%% Cell type:code id: tags:
 
``` python
import scipy.misc
raccoon = np.array(scipy.misc.face())
```
 
%% Cell type:markdown id: tags:
 
Write a script to print shape and dtype the raccoon image. Next plot the image using matplotlib.
 
%% Cell type:code id: tags:
 
``` python
print("shape of raccoon = ", raccoon.shape)
print("dtype of raccoon = ", raccoon.dtype)
```
 
%% Output
 
shape of raccoon = (768, 1024, 3)
dtype of raccoon = uint8
 
%% Cell type:code id: tags:
 
``` python
plt.imshow(raccoon)
```
 
%% Output
 
<matplotlib.image.AxesImage at 0x7f39e00aba58>
 
 
%% Cell type:markdown id: tags:
 
0. Write a script to generate a border around the raccoon image (for example a 20 pixel size black border; black color code is 0 0 0)
 
1. Do it again without losing pixels and generate then a raccoon1 array/image
 
2. 1. Mask the face of the raccoon with a grey circle (centered of radius 240 at location 690 260 of the raccoon1 image; grey color code is for example (120 120 120)). Tip: check the np.indices function.
2. Mask the face of the raccon with a grey square by using NumPy broadcast capabilities (height and width 480 and same center as before)
2. Mask the face of the raccoon with a grey square by using NumPy broadcast capabilities (height and width 480 and same center as before)
 
3. We propose to smooth the image : the value of a pixel of the smoothed image is the the average of the values of its neighborhood (ie the 8 neighbors + itself).
 
%% Cell type:markdown id: tags:
 
### Solution 0
 
Write a script to generate a border around the raccoon image (for example a 20 pixel size black border; black color code is 0 0 0)
 
%% Cell type:code id: tags:
 
``` python
raccoon[0:20, :, :] = 0
raccoon[-20:-1, :, :] = 0
raccoon[:, 0:20, :] = 0
raccoon[:, -20:-1, :] = 0
plt.imshow(raccoon)
```
 
%% Output
 
<matplotlib.image.AxesImage at 0x7f39ce79dbe0>