Issue
I'm learning Python's matplotlib FuncAnimation method but can't get a basic Bayesian conjugates animation to run. When I run this, I just get a blank output in my Jupyter notebook. I also get same result using Google Colab. How do I get animation to run and show?
Note, I could get official animation tutorial scripts to run... It's just an issue with the code below.
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gamma, poisson
np.random.seed(0)
fig, ax = plt.subplots()
line, = ax.plot([], [])
def animate(i):
if i == 0:
x = np.linspace(0, 30, 1000)
alpha = 2
beta = 1
y = gamma.pdf(x, a=alpha, scale=beta)
line.set_data(x, y)
return line,
else:
sample = poisson.rvs(4)
alpha += sample
beta += 1
y = gamma.pdf(x, a=alpha, scale=beta)
line.set_data(x, y)
return line,
%matplotlib notebook
%matplotlib notebook
anim = FuncAnimation(fig, animate, frames=2, blit=True)
plt.show()
Solution
When I create animations in jupyterlab, I specify the following library, which seems to use html5's video function to draw.
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
from IPython.display import HTML
import numpy as np
from scipy.stats import gamma, poisson
np.random.seed(0)
fig, ax = plt.subplots()
line, = ax.plot([], [])
def animate(i):
if i == 0:
x = np.linspace(0, 30, 1000)
alpha = 2
beta = 1
y = gamma.pdf(x, a=alpha, scale=beta)
line.set_data(x, y)
return line,
else:
x = np.linspace(0, 30, 1000)
alpha = 2
beta = 1
sample = poisson.rvs(4)
alpha += sample
beta += 1
y = gamma.pdf(x, a=alpha, scale=beta)
line.set_data(x, y)
return line,
anim = FuncAnimation(fig, animate, frames=2, blit=True)
# plt.show()
plt.close()
HTML(anim.to_html5_video())
Answered By - r-beginners
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.