Ch. 4 Math
Last update: Thu Nov 19 17:20:43 2020 -0600 (49b93b1)
R
library(reticulate)
reticulate::use_condaenv("r-python")
4.1 Functions
Python
# https://www.geeksforgeeks.org/plot-mathematical-expressions-in-python-using-matplotlib/
# Import libraries
import matplotlib.pyplot as plt
import numpy as np
= np.linspace(-6, 6, 50)
x = plt.figure(figsize = (14, 8))
fig
# Plot y = cos(x)
= np.cos(x)
y 'b', label ='cos(x)')
plt.plot(x, y,
# Plot degree 2 Taylor polynomial
= 1 - x**2 / 2
y2 'r-.', label ='Degree 2')
plt.plot(x, y2,
# Plot degree 4 Taylor polynomial
= 1 - x**2 / 2 + x**4 / 24
y4 'g:', label ='Degree 4')
plt.plot(x, y4,
# Add features to our figure
plt.legend() True, linestyle =':')
plt.grid(-6, 6])
plt.xlim([-4, 4])
plt.ylim([
'Taylor Polynomials of cos(x) at x = 0')
plt.title('x-axis')
plt.xlabel('y-axis')
plt.ylabel(
# Show plot
plt.show()
4.2 Functions with Latex labels
Python
# https://www.kaggle.com/sskiing/matplotlib-showcase-examples
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def func(x):
return (x - 3) * (x - 5) * (x - 7) + 85
= 2, 9 # integral limits
a, b = np.linspace(0, 10)
x = func(x)
y
= plt.subplots(dpi=200)
fig, ax 'r', linewidth=2)
plt.plot(x, y, =0)
plt.ylim(ymin
# Make the shaded region
= np.linspace(a, b)
ix = func(ix)
iy = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
verts = Polygon(verts, facecolor='0.9', edgecolor='0.5')
poly
ax.add_patch(poly)
0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$",
plt.text(='center', fontsize=20)
horizontalalignment
0.9, 0.05, '$x$')
plt.figtext(0.1, 0.9, '$y$')
plt.figtext(
'right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom')
ax.xaxis.set_ticks_position(
ax.set_xticks((a, b))'$a$', '$b$'))
ax.set_xticklabels((
ax.set_yticks([]) plt.show()
4.3 Multiple functions in the same plot
Python
import matplotlib.pyplot as plt
import numpy as np
= np.arange(0.0, 2.0, 0.01)
t
= np.sin(2 * np.pi * t)
s1 = np.exp(-t)
s2 = s1 * s2
s3
= plt.subplots(3, 1, sharex=True)
fig, axs # Remove horizontal space between axes
=0)
fig.subplots_adjust(hspace
# Plot each graph, and manually set the y tick values
0].plot(t, s1)
axs[0].set_yticks(np.arange(-0.9, 1.0, 0.4))
axs[0].set_ylim(-1, 1)
axs[1].plot(t, s2)
axs[1].set_yticks(np.arange(0.1, 1.0, 0.2))
axs[1].set_ylim(0, 1)
axs[2].plot(t, s3)
axs[2].set_yticks(np.arange(-0.9, 1.0, 0.4))
axs[2].set_ylim(-1, 1)
axs[ plt.show()
4.4 Overlapping functions
We use subplot
to arrange the two functions. Observe that the y-axis is the same in both functions.
Python
# https://www.python-course.eu/matplotlib_multiple_figures.php
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
def g(t):
return np.sin(t) * np.cos(1/(t+0.1))
= np.arange(0.0, 5.0, 0.1)
t1 = np.arange(0.0, 5.0, 0.02)
t2 212)
plt.subplot('ro', t2, f(t2), 'k')
plt.plot(t1, g(t1), ='b', alpha=0.5, linestyle='dashed', linewidth=0.5)
plt.grid(color plt.show()
4.5 Surface functions
Python
# http://www.scipy-lectures.org/intro/matplotlib/auto_examples/plot_plot3d_ex.html
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
= plt.figure()
fig = Axes3D(fig)
ax = np.arange(-4, 4, 0.25)
X = np.arange(-4, 4, 0.25)
Y = np.meshgrid(X, Y)
X, Y = np.sqrt(X ** 2 + Y ** 2)
R = np.sin(R)
Z
=1, cstride=1, cmap=plt.cm.hot)
ax.plot_surface(X, Y, Z, rstride='z', offset=-2, cmap=plt.cm.hot)
ax.contourf(X, Y, Z, zdir-2, 2)
ax.set_zlim( plt.show()
Python
# https://matplotlib.org/gallery/mplot3d/offset.html#sphx-glr-gallery-mplot3d-offset-py
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
= plt.figure()
fig = fig.gca(projection='3d')
ax
= np.mgrid[0:6*np.pi:0.25, 0:4*np.pi:0.25]
X, Y = np.sqrt(np.abs(np.cos(X) + np.cos(Y)))
Z
+ 1e5, Y + 1e5, Z, cmap='autumn', cstride=2, rstride=2)
ax.plot_surface(X
"X label")
ax.set_xlabel("Y label")
ax.set_ylabel("Z label")
ax.set_zlabel(0, 2)
ax.set_zlim( plt.show()
This is the typical example that you find in all Matlab
books and tutorials.
Python
# https://github.com/matplotlib/matplotlib/blob/master/examples/mplot3d/surface3d_radial.py
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
= plt.figure()
fig = fig.add_subplot(111, projection='3d')
ax
# Create the mesh in polar coordinates and compute corresponding Z.
= np.linspace(0, 1.25, 50)
r = np.linspace(0, 2*np.pi, 50)
p = np.meshgrid(r, p)
R, P = ((R**2 - 1)**2)
Z # Express the mesh in the cartesian system.
= R*np.cos(P), R*np.sin(P)
X, Y # Plot the surface.
=plt.cm.YlGnBu_r)
ax.plot_surface(X, Y, Z, cmap# Tweak the limits and add latex math labels.
0, 1)
ax.set_zlim(r'$\phi_\mathrm{real}$')
ax.set_xlabel(r'$\phi_\mathrm{im}$')
ax.set_ylabel(r'$V(\phi)$')
ax.set_zlabel(
plt.show()
4.6 3D wireframe
Python
# https://github.com/matplotlib/matplotlib/blob/master/examples/mplot3d/wire3d.py
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
= plt.figure()
fig = fig.add_subplot(111, projection='3d')
ax
# Grab some test data.
= axes3d.get_test_data(0.05)
X, Y, Z
# Plot a basic wireframe.
=10, cstride=10)
ax.plot_wireframe(X, Y, Z, rstride
plt.show()
4.7 3D contour plot
Python
# https://matplotlib.org/2.0.2/examples/mplot3d/contour3d_demo.html
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
= plt.figure()
fig = fig.add_subplot(111, projection='3d')
ax = axes3d.get_test_data(0.05)
X, Y, Z = ax.contour(X, Y, Z, cmap=cm.coolwarm)
cset =9, inline=1)
ax.clabel(cset, fontsize
plt.show()
4.8 Machine Learning
This is just one sample of discovering patterns with machine learning.
Python
import numpy as np
from matplotlib import pyplot as plt
from sklearn import neighbors, datasets
from matplotlib.colors import ListedColormap
# Create color maps for 3-class classification problem, as with iris
= ListedColormap(['#FFAAAA','#AAFFAA','#AAAAFF'])
cmap_light = ListedColormap(['#FF0000','#00FF00','#0000FF'])
cmap_bold
= datasets.load_iris()
iris = iris.data[:, :2] # we only take the first two features. We could
X # avoid this ugly slicing by using a two-dim dataset
= iris.target
y = neighbors.KNeighborsClassifier(n_neighbors=1)
knn
knn.fit(X, y)= X[:, 0].min() - .1, X[:, 0].max() + .1
x_min, x_max = X[:, 1].min() - .1, X[:, 1].max() + .1
y_min, y_max = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100))
xx, yy
= knn.predict(np.c_[xx.ravel(), yy.ravel()])
Z
= Z.reshape(xx.shape)
Z
plt.figure()=cmap_light)
plt.pcolormesh(xx, yy, Z, cmap
# Plot also the training points
0], X[:, 1], c=y, cmap=cmap_bold)
plt.scatter(X[:, 'sepal length (cm)')
plt.xlabel('sepal width (cm)')
plt.ylabel('tight')
plt.axis( plt.show()