7. Matplotlib Basics

7.1 Verifying the python version you are using


In [1]:
import sys
print(sys.version)


3.7.0 (default, Aug 20 2018, 21:19:42) 
[Clang 9.1.0 (clang-902.0.39.2)]

At this point anything above python 3.5 should be ok.

7.2 Import numpy and matplotlib


In [2]:
import numpy as np
np.__version__


Out[2]:
'1.15.4'

In [3]:
import matplotlib as mpl
from matplotlib import pyplot as plt
mpl.__version__


Out[3]:
'3.0.2'

Notes:

7.3 Simple plot


In [4]:
x = np.linspace(-3.14, 3.14, num=100)
y = np.sin(x)

plt.plot(x, y)
plt.xlabel('x values')
plt.ylabel('y')
plt.title('y=sin(x)')
plt.show()


Notes:

7.4 Exercice:

Plot other simple functions like the exponential or cosinus

Notes:

8. 3D data visualisation

8.1 Colormaps


In [5]:
x = np.linspace (-1, 1, num =100)
y = np.linspace (-1, 1, num =100)
xx, yy = np.meshgrid (x, y)

z = np.sin(xx**2 + yy**2 + yy)
plt.pcolormesh(x, y, z, shading = 'gouraud')
plt.show()



In [6]:
#change the colormaps

#mpl.rcParams['image.cmap'] = 'viridis'
mpl.rcParams['image.cmap'] = 'jet'
#mpl.rc('image', cmap='jet')
#mpl.rc('image', cmap='hsv')

plt.pcolormesh(x, y, z, shading = 'gouraud')
plt.show()



In [7]:
#use imshow
plt.imshow(z, aspect='auto')
plt.show()


Notes:

8.2 3D Surface


In [8]:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
fig = plt.figure(figsize=(12,8))
ax = fig.gca(projection='3d')
ax.plot_surface(xx, yy, z, rstride=5, cstride=5, cmap=cm.coolwarm, linewidth=1, antialiased=True)
plt.show()


Notes:

8.3 3D Wireframe

Create a numpy array and set the elements in it as you iterate.


In [9]:
fig = plt.figure(figsize=(12,8))
ax = fig.gca(projection='3d')
ax.plot_wireframe(xx, yy, z, rstride=5, cstride=5, antialiased=True)
plt.show()


Notes:

9. Multiple Plots


In [11]:
fig = plt.figure(figsize=(20,15))

#create the subplots
ax = fig.add_subplot(2,2,1)
bx = fig.add_subplot(2,2,2)
cx = fig.add_subplot(2,2,3, projection='3d')
dx = fig.add_subplot(2,2,4, projection='3d')

#the sin
ax.plot(np.linspace(-np.pi,np.pi,100), np.sin(np.linspace(-np.pi,np.pi,100)))
ax.scatter(np.linspace(-np.pi,np.pi,100), np.cos(np.linspace(-np.pi,np.pi,100)))
ax.set_xlabel('x values')
ax.set_ylabel('y')
ax.set_title('y=sin(x)')

#the image
bx.imshow(z, aspect='auto')
bx.set_xlabel('x')
bx.set_ylabel('y')
bx.set_title('Some image')

#the surface
cx.set_xlabel('some x')
cx.set_ylabel('some y')
cx.set_zlabel('some z')
cx.set_title('The surface')
cx.plot_surface(xx, yy, z, rstride=5, cstride=5, cmap=cm.coolwarm, linewidth=1, antialiased=True)

#the wireframe
dx.set_xlabel('some x')
dx.set_ylabel('some y')
dx.set_zlabel('some z')
dx.set_title('The wireframe')
dx.plot_wireframe(xx, yy, z, rstride=4, cstride=4, antialiased=True)

plt.show()


Notes:

10. Exercice:

From what you have leanrt about matplotlib make four subplots of:

- Randome 2D data

- Randome 3D data as colormap

- Gaussian 3D as a surface (np.gaussian)

- Gaussian 3D as a wireframe (np.gaussian)


In [ ]:

Notes: