0

I've been trying to animate the convergence of a binomial p.m.f. to a Poisson one, but couldn't figure it out with matplotlib's animate. Here's my best try:

from random import randint
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()

def animate(i):
    p = 0.01    
    bino = stats.binom(i,p)
    x = np.arange(0,i)
    y1 = bino.pmf(x)
    possion = stats.poisson(i*p)
    y2 = possion.pmf(x)
    ax.clear()
    line1, = ax.plot(x, y1)
    line2, = ax.plot(x, y2)
    ax.set_xlim([0,i])
    ax.set_ylim([0,max(y1)])
    return line1, line2

ani = FuncAnimation(fig, animate, frames=range(10,100), interval=5000, repeat=False)

plt.show()
hrrrrrr5602
  • 103
  • 6
  • 1
    where is `p` defined for your poisson distribution? – Galletti_Lance Jan 21 '22 at 13:53
  • Thanks, it went missing – hrrrrrr5602 Jan 21 '22 at 14:05
  • You also need to define `n` and `bino`. The animation function needs to return the "changed elements", e.g. `line1, = ax.plot(x, y1); line2, = ax.plot(x, y2); return line1, line2` (note the unusual looking commas). You also should set the xlim and ylim before calling the animation (preferably these limits stay fixed during the animation). – JohanC Jan 21 '22 at 14:06
  • Why the unusual commas? It still doesn't seem to work, despite your helpful comments. – hrrrrrr5602 Jan 21 '22 at 14:41
  • [About the commas](https://stackoverflow.com/questions/16037494/x-is-this-trailing-comma-the-comma-operator). Your code does show something, although the `interval=5000` makes things quite slow (5000 milliseconds between steps). (If you are using Jupyter, you might need to set interactivity for matplotlib, default it only shows a still image). – JohanC Jan 21 '22 at 14:57

0 Answers0