Catalog
How To Embed Animation Into Jupyter Notebook

Recently I struggled to choose the right way to write python. I’m not willing to use bloatware such as spyder to write. Since I want to feel very free when I want to start to write. This could be done via text eidter such as sublime text or vs code. However, my another demand is to write the note and code in the same file. This demand could be best solved via jupyter notebook when you want to solve something and show how you solve it.

I have tested the way of animating the plot by using the package Matplotlib. A more natural idea is that can the animated plot be shown in jupyter notebook. After searching in the web I know this couldn’t be solved directly. Different people offer different solutions. I choose the most simple and direct solution (at least in my mind). This is the solution.

Here is a simple examle from this web

1
from matplotlib import animation
2
from IPython.display import HTML
3
4
# First set up the figure, the axis, and the plot element we want to animate
5
fig = plt.figure()
6
ax = plt.axes(xlim=(0, 1), ylim=(-6, 10))
7
line, = ax.plot([], [], lw=1)
8
9
# Initialization function: plot the background of each frame
10
def init():
11
    line.set_data([], [])
12
    return line,
13
14
# Animation function which updates figure data.  This is called sequentially
15
def animate(i):
16
    line.set_data(x, u[i,:])
17
    return line,
18
19
# Call the animator.  blit=True means only re-draw the parts that have changed.
20
anim = animation.FuncAnimation(fig, animate, init_func=init,
21
                               frames=Nt, interval=20, blit=True)
22
23
plt.close(anim._fig)
24
25
# Call function to display the animation
26
HTML(anim.to_html5_video())

I want tp try this method and I hope to use one of my original program which shows the difference between the actual case and harmonic oscillator approximation when a sphere slides down from a semi-circle. I want show show the plot displyed in the jupyter notebook and can be controled via some buttons. This can be realized by directly adding two extra lines into the original program. To show the animation like a video in the jupyter notebook,

1
from IPython.display import HTML
2
HTML(anim.to_html5_video())

Then you will see the following animated video in the explorer
The animated plot

If you want to control the animated plot, you could type

1
HTML(anim.to_jshtml())

then you can control the animated plot by hand.

Interactive plot

Author: Knifelee
Link: https://knifelees3.github.io/2020/02/02/A_En_HowToEmbedAnimationIntoJupyterNotebook/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶

Comment