python animation画概率密度函数填充动画

import numpy as np
import matplotlib.pyplot as plt
import math
from matplotlib import animation

def normal_distribution(x, mu, sigma):
    return np.exp(-1 * ((x - mu) ** 2) / (2 * (sigma ** 2))) / (math.sqrt(2 * np.pi) * sigma)

mu = 0
sigma = 1
x = np.linspace(mu - 6 * sigma, mu + 6 * sigma, 200)
y = normal_distribution(x, mu, sigma)

fig, ax = plt.subplots()
xdata = []
ydata = []

def upadte(frame):
    xdata.append(frame)
    ydata.append(normal_distribution(frame, mu, sigma))
    plt.fill_between(xdata, ydata, [0], color='blue', alpha=0.1)
    line.set_data(xdata, ydata)
    return line,

def init():
    ax.set_xlim(-6, 6)
    ax.set_ylim(0, 0.5)
    return line,

line, = plt.plot(xdata, ydata, 'r-')
ani = animation.FuncAnimation(
    fig=fig,
    func=upadte,
    frames=np.linspace(mu - 6 * sigma, mu + 6 * sigma, 200),
    init_func=init,
    interval=10,
    repeat=False
)
ax.set_xlabel("X")
ax.set_ylabel("Y")
plt.grid()
plt.show()
ani.save('ani_1.gif')

猜你喜欢

转载自blog.csdn.net/s1hjf/article/details/127830790