使用 matplotlib 为正态分布、高斯分布、指数分布和伽马分布创建动画的问题

Issues with creating an animation using matplotlib for normal, gaussian, exponential and gamma distributions

我有下面的代码来为高斯分布、正态分布、指数分布和 Gamma 分布创建动画:

import matplotlib.animation as animation
import numpy as np 
import matplotlib.pyplot as plt 
fig = plt.figure()

def update(curr):
        if curr == n: 
            a.event_source.stop()
        plt.cla()
        plt.axis([-7,21,0,0.6])
        bins = np.arange(-7,21,1)
        plt.hist(x[:curr], bins=bins)
        plt.gca().set_title('Sampling the' + " "+distribution+" " + 'Distribution')
        plt.gca().set_ylabel('Frequency')
        plt.gca().set_xlabel('Value')
        plt.annotate('n = {}'.format(curr), [3,27])

n = 10000
x = np.random.normal(-2.5, 1, 10000)
distribution = 'normal'
a1 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.gamma(2, 1.5, 10000)
distribution = 'gamma'
a2 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.exponential(2, 10000)+7
distribution = 'exponential'
a3 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.uniform(14,20, 10000)
distribution = 'uniform'
a4 = animation.FuncAnimation(fig, update, interval=100)

我想创建 4 个动画,一个是正态分布,一个是高斯分布,一个是指数分布,一个是伽马分布。

但是,当我 运行 此代码时,我得到一个空白图表(只有 y 轴和 x 轴)。

谁能告诉我哪里错了?

我稍微重新安排了您的代码以使动画正常工作。
动画在 animate() 函数中更新,我使用 plot_histogram() 函数来避免重复。
逐帧更新的参数是 i,在本例中用于增加 np.random._ 函数绘制的样本数。

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

fig, ax = plt.subplots(2, 2, figsize = (8, 8))
bins = np.arange(-7,21,1)

def animate(i):
        normal_data = np.random.normal(-2.5, 1, 100*i)
        plot_histogram(ax[0, 0], normal_data, 'Sampling the Normal Distribution', 'n = {}'.format(100*i))

        gamma_data = np.random.gamma(2, 1.5, 100*i)
        plot_histogram(ax[0, 1], gamma_data, 'Sampling the Gamma Distribution', 'n = {}'.format(100*i))

        exponential_data = np.random.exponential(2, 100*i)+7
        plot_histogram(ax[1, 0], exponential_data, 'Sampling the Exponential Distribution', 'n = {}'.format(100*i))

        uniform_data = np.random.uniform(14,20, 100*i)
        plot_histogram(ax[1, 1], uniform_data, 'Sampling the Uniform Distribution', 'n = {}'.format(100*i))

def plot_histogram(ax, data, title, annotation):
    ax.cla()
    ax.hist(data, bins = bins)
    ax.set_title(title)
    ax.set_ylabel('Frequency')
    ax.set_xlabel('Value')
    ax.annotate(annotation, [3, 27])

ani = animation.FuncAnimation(fig, animate, frames = 11, interval = 200)

plt.show()

使用这段代码我得到了这个动画: