使用d2l包:
import math
import numpy as np
from d2l import torch as d2l
import matplotlib.pyplot as plt
def normal(x, mu, sigma):
p = 1 / math.sqrt(2 * math.pi * sigma ** 2)
return p * np.exp(-0.5 / sigma ** 2 * (x - mu) ** 2)
# 创建一个 NumPy 数组 x,其中包含从 -7 到 7 的数值,步长为 0.01
x = np.arange(-7, 7, 0.01)
# 均值和标准差对
params = [(0, 1), (0, 2), (3, 1)]
# figsize设置图形的尺寸大小为宽度 4.5 英寸,高度 2.5 英寸
d2l.plot(x, [normal(x, mu, sigma) for mu, sigma in params], xlabel='x',
ylabel='p(x)', figsize=(4.5, 2.5),
legend=[f'mean {mu}, std {sigma}' for mu, sigma in params])
plt.show()
结果图:
不使用d2l包,用plt的plot函数画图:
import math
import numpy as np
import matplotlib.pyplot as plt
def normal(x, mu, sigma):
p = 1 / math.sqrt(2 * math.pi * sigma ** 2)
return p * np.exp(-0.5 / sigma ** 2 * (x - mu) ** 2)
# 创建一个 NumPy 数组 x,其中包含从 -7 到 7 的数值,步长为 0.01
x = np.arange(-7, 7, 0.01)
# 均值和标准差对
params = [(0, 1), (0, 2), (3, 1)]
# 绘制曲线
plt.figure(figsize=(4.5, 2.5)) # 设置图形尺寸
for mu, sigma in params:
y = normal(x, mu, sigma)
plt.plot(x, y, label=f'mean {mu}, std {sigma}')
# 添加标签和标题
plt.xlabel('x')
plt.ylabel('p(x)')
plt.title('Normal Distribution')
# 添加网格
plt.grid(True)
# 添加图例,plt.legend() 函数用于在 matplotlib 绘图中添加图例,用于标识不同数据系列或不同曲线的含义。
plt.legend()
plt.show()
结果图: