创建一个函数def norm_curve (mu, sigma , x) 在同一个 figure 里面绘制 x ∼ N(0, 1), x ∼ N(2, 1), x ∼ N(0, 2) 的曲线图。增加网格线,图例,并依次标注(annoate/text)三个曲线的均值, 方差
时间: 2024-05-02 20:18:58 浏览: 35
和分布名称。
```python
import matplotlib.pyplot as plt
import numpy as np
def norm_curve(mu, sigma, x):
fig, ax = plt.subplots(figsize=(8, 5))
ax.grid(True)
ax.set_title('Normal Distribution')
ax.set_xlabel('X')
ax.set_ylabel('Probability Density')
y1 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-0.5 * ((x - mu) / sigma) ** 2)
ax.plot(x, y1, label='N({},{})'.format(mu, sigma))
ax.annotate('Mean: {}\nVariance: {}\nDistribution: N({}, {})'.format(mu, sigma, mu, sigma), xy=(mu, 0.4), xytext=(mu + 1, 0.5), arrowprops=dict(facecolor='black', shrink=0.05))
if mu != 0:
y2 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-0.5 * ((x - (mu + 2)) / sigma) ** 2)
ax.plot(x, y2, label='N({},{})'.format(mu + 2, sigma))
ax.annotate('Mean: {}\nVariance: {}\nDistribution: N({}, {})'.format(mu + 2, sigma, mu + 2, sigma), xy=(mu + 2, 0.4), xytext=(mu + 3, 0.5), arrowprops=dict(facecolor='black', shrink=0.05))
if sigma != 1:
y3 = 1 / ((2 * np.pi) ** 0.5 * sigma) * np.exp(-0.5 * (x ** 2 / sigma ** 2))
ax.plot(x, y3, label='N({},{})'.format(mu, sigma * 2))
ax.annotate('Mean: {}\nVariance: {}\nDistribution: N({}, {})'.format(mu, sigma * 2, mu, sigma * 2), xy=(0, 0.4), xytext=(1, 0.5), arrowprops=dict(facecolor='black', shrink=0.05))
ax.legend(loc='best')
x = np.linspace(-10, 10, 1000)
norm_curve(0, 1, x)
```
输出:
![image.png](attachment:image.png)
阅读全文