Embedding Matplotlib Animations in Python (google colab notebook)
Asked Answered
C

5

14

I am trying to show a gif file in google's colab.research. I was able to save the file in the directory with the following path name /content/BrowniamMotion.gif but I don't know how to show this GIF in my notebook to present.

The code to generate the GIF so far, in case someone can manipulate it not to save the GIF but rather to animate it directly into the google colab file was,

# Other Brownian Motion
from math import *
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation

fig = plt.figure(figsize=(8,6))
ax = plt.axes(projection='3d')

N=10
#val1 = 500

x=500*np.random.random(N)
y=500*np.random.random(N)

z=500*np.random.random(N)

def frame(w):
    ax.clear()

    global x,y,z
    x=x+np.random.normal(loc=0.0,scale=50.0,size=10)
    y=y+np.random.normal(loc=0.0,scale=50.0,size=10)
    z=z+np.random.normal(loc=0.0,scale=50.0,size=10)


    plt.title("Brownian Motion")
    ax.set_xlabel('X(t)')
    ax.set_xlim3d(-500.0,500.0)
    ax.set_ylabel('Y(t)')
    ax.set_ylim3d(-500.0,500.0)
    ax.set_zlabel('Z(t)')


     ax.set_zlim3d(-500.0,500.0) 

        plot=ax.scatter

3D(x, y, z, c='r')


    return plot


anim = animation.FuncAnimation(fig, frame, frames=100, blit=False, repeat=True)

anim.save('BrowniamMotion.gif', writer = "pillow", fps=10 )  

Sorry if this question is badly, stated. I am new to Python and using colab research.

Citarella answered 8/4, 2020 at 15:11 Comment(0)
B
29

For Colab it is easiest to use 'jshtml' to display matplotlib animation.

You need to set it up with

from matplotlib import rc
rc('animation', html='jshtml')

Then, just type your animation object. It will display itself

anim

Here's a workable colab of your code.

It has a slider where you can run back and forth at any point in time.

Bachelorism answered 9/4, 2020 at 4:43 Comment(5)
why do you get a duplicated frame displayed below the animation?Citronellal
@JuanAlejandroGalvis use IPython.display.display(anim) to avoid the duplicated frameTamasha
Does this still work on google colab? I just executed it and it does not animate anything...Lille
It's still work, but the duplicated frame keeps. IPython.display.display(anim) didn't remove the duplicated frame for me.Quaver
@JuanAlejandroGalvis Please have a look at my answer, I have a workaround for the duplicated frame problem.Orthopedist
C
2

Check this link out on using the HTML to get it to work http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/ .

I didn't embed a link but instead imbedded a HTML video that got it to work.

# Other Brownian Motion
from math import *
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
from IPython.display import HTML

fig = plt.figure(figsize=(8,6))
ax = plt.axes(projection='3d')

N=10
val1 = 600

x=val1*np.random.random(N)
y=val1*np.random.random(N)
z=val1*np.random.random(N)

def frame(w):
    ax.clear()

    global x,y,z
    x=x+np.random.normal(loc=0.0,scale=50.0,size=10)
    y=y+np.random.normal(loc=0.0,scale=50.0,size=10)
    z=z+np.random.normal(loc=0.0,scale=50.0,size=10)


    plt.title("Brownian Motion")
    ax.set_xlabel('X(t)')
    ax.set_xlim3d(-val1,val1)
    ax.set_ylabel('Y(t)')
    ax.set_ylim3d(-val1,val1)
    ax.set_zlabel('Z(t)')
    ax.set_zlim3d(-val1,val1) 

    plot=ax.scatter3D(x, y, z, c='r')


    return plot


anim = animation.FuncAnimation(fig, frame, frames=100, blit=False, repeat=True)

anim.save('BrowniamMotion.gif', writer = "pillow", fps=10 )
HTML(anim.to_html5_video())

Essentially all we did hear was add,

from IPython.display import HTML to the premable and then add the line HTML(anim.to_html5_video()). This code then produces a video and saves the gif.

Citarella answered 8/4, 2020 at 15:26 Comment(0)
C
2

Using the same authors git repository seems like we have a solution to embed the plots as GIFs ( Save Matplotlib Animations as GIFs ).

#!apt install ffmpeg
#!brew install imagemagick

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

from matplotlib import animation, rc
from IPython.display import HTML, Image # For GIF

rc('animation', html='html5')
np.random.seed(5)


# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)


def generateRandomLines(dt, N):
    dX = np.sqrt(dt) * np.random.randn(1, N)
    X = np.cumsum(dX, axis=1)

    dY = np.sqrt(dt) * np.random.randn(1, N)
    Y = np.cumsum(dY, axis=1)

    lineData = np.vstack((X, Y))

    return lineData


# Returns Line2D objects
def updateLines(num, dataLines, lines):
    for u, v in zip(lines, dataLines):
        u.set_data(v[0:2, :num])

    return lines

N = 501 # Number of points
T = 1.0
dt = T/(N-1)


fig, ax = plt.subplots()

data = [generateRandomLines(dt, N)]

ax = plt.axes(xlim=(-2.0, 2.0), ylim=(-2.0, 2.0))

ax.set_xlabel('X(t)')
ax.set_ylabel('Y(t)')
ax.set_title('2D Discretized Brownian Paths')

## Create a list of line2D objects
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1])[0] for dat in data]


## Create the animation object
anim = animation.FuncAnimation(fig, updateLines, N+1, fargs=(data, lines), interval=30, repeat=True, blit=False)

plt.tight_layout()
plt.show()

# Save as GIF
anim.save('animationBrownianMotion2d.gif', writer='pillow', fps=60)

Image(url='animationBrownianMotion2d.gif')
## Uncomment to save the animation
#anim.save('brownian2d_1path.mp4', writer=writer)

enter image description here

Citarella answered 8/4, 2020 at 20:20 Comment(0)
V
1

Duplicate frame that is displaying along with animated frame can be avoided by simply using the following magic command:

%matplotlib notebook

If you again want to go to previous state and wish to show duplicate frame then you have to remove or comment above magic command and restart the kernel.

Vietcong answered 30/5, 2024 at 15:47 Comment(0)
O
0

Here's a simple solution, based on @korakot answer, that solves the problem of having the extra frame after the animation:

from matplotlib import animation
from IPython.display import HTML

def frame(f):
    ax.clear()
    ax.plot(...your code here...)

fig = plt.figure()
ax = plt.axes()
anim = animation.FuncAnimation(fig, frame, frames=100)
plt.close()
HTML(anim.to_jshtml())

Note that if HTML(...) is not on the last line of the colab cell, in won't be automatically displayed (unless you explicitly call IPython.display.display()).

Orthopedist answered 8/5, 2024 at 15:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.