Matplotlib Exercises
Exercise 11.1: Plotting a function
import matplotlib.pyplot as plt
import numpy as np
def f(x):
"""Compute f(x)"""
part1 = np.sin(x - 2)
part2 = np.exp(-np.power(x, 2))
f = np.power(part1, 2) * part2
return f
x = np.linspace(0, 2, 1000)
y = [f(i) for i in x]
plt.plot(x, y, 'b-', label = "f(x)")
plt.title("Plotting a function", fontsize = 24)
plt.xlabel("x", fontsize = 24)
plt.ylabel("f(x)", fontsize = 24)
plt.legend()
plt.savefig("Plotting a function.png")
plt.show()
Result of Exercise 11.1
Exercise 11.2: Data
import matplotlib.pyplot as plt
import numpy as np
from scipy import linalg
num = 10
X = np.random.randint(-num, num, 200).reshape(20, 10)
b = np.random.randint(-num, num, 10).reshape(10, 1)
z = np.random.normal(loc = 0, scale = 1, size = 20).reshape(20, 1)
y = np.dot(X, b) + z
# Least squares, solve (X.T)Xb = (X.T)y
b_estimate = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)
plt.plot(b, 'ro', b_estimate, 'bx')
plt.title("Data", fontsize = 24)
plt.xlabel("index", fontsize = 24)
plt.ylabel("value", fontsize = 24)
plt.legend(["True param", "Estimated param"])
plt.savefig("Data.png")
plt.show()
Result of Exercise 11.2
Exercise 11.3: Histogram and density estimation
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
n = 10000
Ez = 0
Dz = 1
z = np.random.normal(Ez, Dz, n)
z = np.sort(z)
kde = stats.gaussian_kde(z)
plt.plot(z, kde(z), "r-", label = "Gaussian Kernel Density")
plt.hist(z, bins = 25, edgecolor = "black", normed = True, color = "b")
plt.legend()
plt.savefig("Histogram and density estimation.png")
plt.show()
Result of Exercise 11.3