matplotlibanimationgifgoogle-colaboratoryanimated-gif

Embedding Matplotlib Animations in Python (google colab notebook)


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.


Solution

  • 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.