matplotlib练习

题目来自高级编程课程的课件。


# 11.1 Plotting a function
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import math

# Data for plotting
x = np.arange(0.0, 2.0, 0.01)
y = (np.sin(x-2)**2)*(math.e**(-x**2))

# Note that using plt.subplots below is equivalent to using
# fig = plt.figure() and then ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ax.plot(x, y)

ax.set(xlabel='x', ylabel='f(x)',
       title='f(x) = [(sin(x-2))^2]*e^(-x^2)')
ax.grid()

plt.show()

显示效果:



这道题里解了一个最小二乘问题。

import numpy as np
import matplotlib.pyplot as plt
n = 20
m = 10
X = np.empty([n, m])
for i in range(n):
    row = np.random.normal(10, 1, m)
    X[i] = row

b = np.random.normal(5, 1, m)
z = np.random.normal(0, 1, n)

y = np.matmul(X, b) + z
print(y)

b_ = np.linalg.lstsq(X, y, rcond=None)[0]
print(b)
print(b_)

x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

plt.plot(x, b, 'b', label='true data', markersize=10)
plt.plot(x, b_, 'r', label='estimated data', markersize=10)
plt.legend()
plt.show()

显示效果:




import numpy as np
from scipy import stats
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

z = 100+10*np.random.randn(10000)
n, bins, patches = plt.hist(z, 50, normed=1, facecolor='green', alpha=0.75)

plt.ylabel('Probability')
plt.title(r'histogram')
plt.axis([60, 140, 0, 0.05])
plt.grid(True)

kernel = stats.gaussian_kde(z)

xs = np.linspace(60, 140)
plt.plot(xs, kernel(xs))

plt.show()

显示效果:




猜你喜欢

转载自blog.csdn.net/qq_35783731/article/details/80489658
今日推荐