Matplotlib习题

Matplotlib

Exercise 11-1

代码

import matplotlib.pyplot as plt  
import numpy as np
from math import *
figure,axes = plt.subplots(1,1,figsize=(5,4))
x_array = np.linspace(0,2,200)
# x在[0,2)中取20个点
y_array = np.power(np.sin(x_array - 2), 2) * np.exp(- np.power(x_array, 2))
#对于每个x,计算出对应的y

axes.plot(x_array, y_array, label='$sin^2(x-2)*e^{-x^2}$')
axes.set_xlim((0, 2))
axes.set_ylim((0, 1))
# 设置x轴和y轴的取值范围
axes.set_xlabel('myX')
axes.set_ylabel('myY')
axes.set_title('Exercise 11-1')
plt.tight_layout()
# 自动调整绘图区间距,大小
plt.plot(x_array,y_array,'r')

plt.show()

结果

Exercise 11-1

Exercise 11-2

代码

from scipy import linalg
import numpy as np
import matplotlib.pyplot as plt

matrixX = np.random.random((20,10))
# 创建20x10的矩阵x
vectorB = np.random.random((10,1))
# 随便创造一个10x1的向量b
vectorZ = np.random.normal(size = (20,1))
# 用正态分布创建一个20x1的向量z
vectorY = np.dot(matrixX, vectorB) + vectorZ
# 计算y=xb+z
estimatorB = np.linalg.lstsq(matrixX,vectorY)[0]
# 计算使Xb-y的frobenius范数最小的b

# 接下来画图
figure, axes = plt.subplots(1, 1, figsize = (5, 4))
axes.set_xlabel('index')
axes.set_ylabel('value')
axes.plot(vectorB, 'rx', label = 'True coefficients')
axes.plot(estimatorB, 'bo', label = 'Estimated coefficients')
plt.legend()
plt.show()

结果

Exercise 11-2

Exercise 11-3

代码

import numpy as np
from scipy import stats
import matplotlib.pylab as plt

n_basesample = 10000
np.random.seed(8765678)
xn = np.random.randn(n_basesample)

gkde=stats.gaussian_kde(xn)
ind = np.linspace(-7,7,101)
kdepdf = gkde.evaluate(ind)

figure, axes = plt.subplots(1, 1, figsize=(5,4))

axes.hist(xn, bins=25, normed=1)
# plot estimated density
axes.plot(ind, kdepdf, label='kde', color="g")
axes.set_title('Kernel Density Estimation')
plt.legend()
plt.show()

结果

Exercise 11-3

猜你喜欢

转载自blog.csdn.net/qq_39178023/article/details/80464754