首页 > 解决方案 > 使用 matplotlib 针对正态分布、高斯分布、指数分布和伽马分布创建动画的问题

问题描述

我有以下代码来为高斯、正态、指数和伽玛分布创建动画:

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 轴)。

谁能告诉我哪里出错了?

标签: pythonnumpymatplotlibanimationvisualization

解决方案


我稍微重新排列了您的代码以使动画正常工作。
动画在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()

有了这段代码,我得到了这个动画:

在此处输入图像描述


推荐阅读