python matplotlib作业

代码:

import matplotlib as mpt
import pylab
import math
import numpy as np
from scipy.optimize import leastsq
from scipy import stats

#11.1 Plotting a function
x = np.linspace(0, 2, 1000)
y = np.sin((x-2)*np.exp(-x**2))**2

mpt.pyplot.plot(x, y, 'r')
mpt.pyplot.xlabel('x')
mpt.pyplot.ylabel('y')
mpt.pyplot.title('Plotting a function')
mpt.pyplot.show()

#11.2 Data
X = np.random.randint(1, 10, size = (20, 10))
b = np.random.randint(1, 10, size = (10, 1))
z = np.random.normal(size = (20, 1))
y = np.dot(X, b) + z

def error(p, X, y):
    return (np.dot(X, p.reshape(10, 1)) - y).reshape(-1)

m_b, s= leastsq(error, b, args=(X, y))

index = range(10)

mpt.pyplot.scatter(index, b, marker = 'x', label = 'True')
mpt.pyplot.scatter(index, m_b, label = 'estimator')
mpt.pyplot.xlabel('index')
mpt.pyplot.ylabel('value')
mpt.pyplot.title('Data')
mpt.pyplot.legend()
mpt.pyplot.show()

#11.3 Histogram and density estimation

z = np.random.normal(1, 10, size=(1000))
kde = stats.gaussian_kde(z)
ind = np.linspace(-30, 30, 100)
kp = kde.evaluate(ind)

mpt.pylab.figure()

mpt.pylab.hist(z, bins=25, normed=True, color='b', edgecolor = 'black')
mpt.pylab.plot(ind, kp, label = 'KDE', color = 'r' )
mpt.pylab.title('Histogram and density estimation')
mpt.pylab.legend()
mpt.pylab.show()


结果:

python matplotlib作业

python matplotlib作业

python matplotlib作业