Probability Distribution Animation

Let’s enjoy below probability distributions including normal distribution, gamma distribution, exponential distribution and uniform distribution. Each distribution is split into 20 data bins, animated over 200 steps

You can adjust the animation to your liking by modifying the source code below

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

# generate 4 random variables from the random, gamma, exponential, and uniform distribution
x1 = np.random.normal(0, 1, 200)
x2 = np.random.gamma(2, 1, 200)
x3 = np.random.exponential(2, 200)
x4 = np.random.uniform(0, 1, 200)

titles = np.array(['Normal', 'Gamma', 'Exponential', 'Uniform']).reshape(2,2)
fig, axs = plt.subplots(len(titles), len(titles), figsize=(8,8))

for i in range(len(titles)):
axs[i,1].get_yaxis().set_visible(False)

_, bins_normal = np.histogram(x1, bins = 20)
_, bins_gamma = np.histogram(x2, bins = 20)
_, bins_exponential = np.histogram(x3, bins = 20)
_, bins_uniform = np.histogram(x4, bins = 20)

n = 200
def update(curr, hist, x, bins, axis, title):
# check if animation is at the last frame, and if so, stop the animation
if curr == n:
animations[title].event_source.stop()

hist.cla()
hist.hist(x[:curr], bins=bins, alpha=0.8)

# Set the axes limits
hist.axis(axis)

hist.set_title(title)

from functools import *
animations = {}
animations[titles[0,0]] = animation.FuncAnimation(fig, partial(update, hist=axs[0,0], x=x1, bins=bins_normal, axis=[-4,4,0,40],
title=titles[0,0]), interval=100, save_count=n)
animations[titles[0,1]] = animation.FuncAnimation(fig, partial(update, hist=axs[0,1], x=x2, bins=bins_gamma, axis=[0,9,0,40],
title=titles[0,1]), interval=100, save_count=n)
animations[titles[1,0]] = animation.FuncAnimation(fig, partial(update, hist=axs[1,0], x=x3, bins=bins_exponential, axis=[0,12,0,50],
title=titles[1,0]), interval=100, save_count=n)
animations[titles[1,1]] = animation.FuncAnimation(fig, partial(update, hist=axs[1,1], x=x4, bins=bins_uniform, axis=[0,1,0,50],
title=titles[1,1]), interval=100, save_count=n)

Một suy nghĩ 1 thoughts on “Probability Distribution Animation

  1. Pingback: Probability Distribution Animation – Century R&D Investment Institute

Bình luận về bài viết này