I am trying to put animations in an iPython notebook and am not finding a solution. I saw one post that discussed using interactive widgets, but there are a couple problems that I have with this: First, every example I see with widgets uses a slider or some other input, whereas I just want the animation to run automatically when the cell is run. Second, all the documentation seems out of date on Jupyter's site--whenever I download and run their notebooks I get these messages about certain modules being deprecated and then later in the file something fails to run, presumably because they're trying to import and access files that no longer exist.
I've seen a few other pages on the topic but they often require downloading binaries or other modules, but I'm partly using this to teach some students Math and I've gotten them to download Anaconda--I was hoping to not further confuse the issue by making them also download and install more complicated things all while spending time not talking about the Math.
So in short, is there a way that I can create animations in an iPython notebook that only require the use of simple import commands that will run out-of-the-box so to speak with the software that comes from Anaconda?
[Edit: I should also note that I've used Tkinter to make animations, and I could make one in matplotlib I'm sure. So if there were a way to get the animations you produce with those to render in an iPython notebook, that would certainly be a working solution for me.]
[Further edit: I suppose I could also say what I am hoping to animate at the moment, although I really want to be pretty flexible about the range of things I could animate if I decide to. Right now I'm trying to make a digital clock that displays each digit in Sumerian base-60 numerals to illustrate a different counting and base system. So it should initially display | then after a second || and so on until ten gets represented as < and so on until eventually the clock ticks over to a minute where it now displays |:| to represent one minute, one second.]
[Note to future humans: If you're implementing some animation and are willing to publicly host it, please leave a link to it in the comments! I'm curious to see how people are making animations these days, and also a little curious to see what they're animating.]
Some options you have for animating plots in Jupyter/IPython, using matplotlib:
Using display in a loop Use IPython.display.display(fig) to display a figure in the output. Using a loop you would want to clear the output before a new figure is shown. Note that this technique gives in general not so smooth resluts. I would hence advice to use any of the below.
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
from IPython.display import display, clear_output
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
for i in range(len(x)):
animate(i)
clear_output(wait=True)
display(fig)
plt.show()
%matplotlib notebook Use IPython magic %matplotlib notebook to set the backend to the notebook backend. This will keep the figure alive instead of displaying a static png file and can hence also show animations.
Complete example:
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
plt.show()
%matplotlib tk Use IPython magic %matplotlib tk to set the backend to the tk backend. This will open the figure in a new plotting window, which is interactive and can thus also show animations.
Complete example:
%matplotlib tk
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
plt.show()
Convert animation to mp4 video (option mentionned by #Perfi already):
from IPython.display import HTML
HTML(ani.to_html5_video())
or use plt.rcParams["animation.html"] = "html5" at the beginning of the notebook.
This will require to have ffmpeg video codecs available to convert to HTML5 video. The video is then shown inline. This is therefore compatible with %matplotlib inline backend. Complete example:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["animation.html"] = "html5"
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
ani
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
from IPython.display import HTML
HTML(ani.to_html5_video())
Convert animation to JavaScript:
from IPython.display import HTML
HTML(ani.to_jshtml())
or use plt.rcParams["animation.html"] = "jshtml" at the beginning of the notebook.
This will display the animation as HTML with JavaScript. This highly compatible with most new browsers and also with the %matplotlib inline backend. It is available in matplotlib 2.1 or higher.
Complete example:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["animation.html"] = "jshtml"
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
ani
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
from IPython.display import HTML
HTML(ani.to_jshtml())
You may find this tutorial interesting.
If you can turn what you need into a matplotlib animation, and I'm fairly sure from your description that it's possible, you can then use
from matplotlib import rc, animation
rc('animation', html='html5')
and display your animation using
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=N, interval=20, blit=True)
anim
Might come in handy!
Jupyter widgets is a good way of displaying animations. The code below displays an animated gif.....
from ipywidgets import Image
from IPython import display
animatedGif = "animatedGifs/01-progress.gif" #path relative to your notebook
file = open(animatedGif , "rb")
image = file.read()
progress= Image(
value=image,
format='gif',
width=100,
height=100)
display.display(progress)
You can close this animation using:
progress.close()
N.B. I found a few nice animated gifs from http://www.downgraf.com/inspiration/25-beautiful-loading-bar-design-examples-gif-animated/.
I had a similar problem, and this question helped me get started. I put together a notebook that illustrates using FuncAnimation along with good explanations of why the notebook does some things the way it does. It also has links to instructions on FFmpeg. It also has links to the examples I used in developing and understanding of animations. You can view my contribution at:
Animation Illustration
For your question, you might find interactive sliders a better tool. I also created a notebook which demonstrates interactive widgets in Jupyter. It is available here; however, the interactive parts don't work there.
Both are available in a GitHub Repostory
Related
I am trying to render an animation of rotating a 3d graph, but the animation is not working, even if I try to use the code given here: https://matplotlib.org/3.5.0/gallery/mplot3d/rotate_axes3d_sgskip.html
The output I get is one static image and <Figure size 432x288 with 0 Axes> repeated multipe times over and over again.
I am using anaconda, jupyter notebooks and also tried using google colab... what is going wrong and how can I fix this? Thank you very much!
I ran into a similar issue before, replacing "%matplotlib inline" with "%matplotlib notebook" in the given code solved it for me.
Since you are using Jupyter Notebook, you need to install ipympl and execute the following command on a cell at the top of your notebook: %matplotlib widget. This will enable an interactive frame which is going to wrap the matplotlib figure in the output cell.
Then, you need to use matplotlib's FuncAnimation:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# load some test data for demonstration and plot a wireframe
X, Y, Z = axes3d.get_test_data(0.1)
ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)
def animate(angle):
ax.view_init(30, angle)
ani = FuncAnimation(fig, animate, frames=range(360))
Add %matplotlib notebook in the cell of Jupyter notebook for an interactive backend.
Execute the below cell, it should work
%matplotlib notebook
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# load some test data for demonstration and plot a wireframe
X, Y, Z = axes3d.get_test_data(0.1)
ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)
# rotate the axes and update
for angle in range(0, 360):
ax.view_init(30, angle)
plt.draw()
plt.pause(.001)
Using Jupyter Notebook, I can create an animated plot (based on this sample code):
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def init():
line.set_ydata([np.nan] * len(x))
return line,
def animate(i):
line.set_ydata(np.sin(x + i / 100)) # update the data.
return line,
ani = animation.FuncAnimation(
fig, animate, init_func=init, interval=2, blit=True, save_count=50)
plt.show()
Is it possible to do so in Visual Studio Code's notebook editor? I think it involves the magic %matplotlib notebook mode which VS Code does not seem to support, but I don't know if there is an alternative.
Looks as though vscode supports ipywidgets (https://github.com/microsoft/vscode-python/issues/3429). So you can use the ipympl backend to matplotlib.
To use it you can use the %matplotlib ipympl magic.
%matplotlib notebook does some javascript injection that is very specific to jupyter notebook, so it will not work in vscode or even jupyter lab.
I am working on a project that involves generating a matplotlib animation using pyplot.imshow for the frames. I am doing this in a jupyter notebook. I have managed to get it working, but there is one annoying bug (or feature?) left. After the animation is created, Jupyter shows the last frame of the animation in the output cell. I would like the output to include the animation, captured as html, but not this final frame. Here is a simple example:
import numpy as np
from matplotlib import animation
from IPython.display import HTML
grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))
ax1 = fig1.add_subplot(1,1,1)
def animate(i):
grid[i,i]=1
ax1.imshow(grid)
return
ani = animation.FuncAnimation(fig1, animate,frames=10);
html = HTML(ani.to_jshtml())
display(html)
I can use the capture magic, but that suppresses everything. This would be OK, but my final goal is to make this public, via binder, and make it as simple as possible for students to use.
I have seen matplotlib animations on the web that don't seem to have this problems, but those used plot, rather than imshow, which might be an issue.
Any suggestions would be greatly appreciated.
Thanks,
David
That's the answer I got from the same thing I was looking for in 'jupyter lab'. Just add plt.close().
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML
grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))
ax1 = fig1.add_subplot(1,1,1)
def animate(i):
grid[i,i]=1
ax1.imshow(grid)
return
ani = animation.FuncAnimation(fig1, animate,frames=10);
html = HTML(ani.to_jshtml())
display(html)
plt.close() # update
I am trying to put animations in an iPython notebook and am not finding a solution. I saw one post that discussed using interactive widgets, but there are a couple problems that I have with this: First, every example I see with widgets uses a slider or some other input, whereas I just want the animation to run automatically when the cell is run. Second, all the documentation seems out of date on Jupyter's site--whenever I download and run their notebooks I get these messages about certain modules being deprecated and then later in the file something fails to run, presumably because they're trying to import and access files that no longer exist.
I've seen a few other pages on the topic but they often require downloading binaries or other modules, but I'm partly using this to teach some students Math and I've gotten them to download Anaconda--I was hoping to not further confuse the issue by making them also download and install more complicated things all while spending time not talking about the Math.
So in short, is there a way that I can create animations in an iPython notebook that only require the use of simple import commands that will run out-of-the-box so to speak with the software that comes from Anaconda?
[Edit: I should also note that I've used Tkinter to make animations, and I could make one in matplotlib I'm sure. So if there were a way to get the animations you produce with those to render in an iPython notebook, that would certainly be a working solution for me.]
[Further edit: I suppose I could also say what I am hoping to animate at the moment, although I really want to be pretty flexible about the range of things I could animate if I decide to. Right now I'm trying to make a digital clock that displays each digit in Sumerian base-60 numerals to illustrate a different counting and base system. So it should initially display | then after a second || and so on until ten gets represented as < and so on until eventually the clock ticks over to a minute where it now displays |:| to represent one minute, one second.]
[Note to future humans: If you're implementing some animation and are willing to publicly host it, please leave a link to it in the comments! I'm curious to see how people are making animations these days, and also a little curious to see what they're animating.]
Some options you have for animating plots in Jupyter/IPython, using matplotlib:
Using display in a loop Use IPython.display.display(fig) to display a figure in the output. Using a loop you would want to clear the output before a new figure is shown. Note that this technique gives in general not so smooth resluts. I would hence advice to use any of the below.
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
from IPython.display import display, clear_output
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
for i in range(len(x)):
animate(i)
clear_output(wait=True)
display(fig)
plt.show()
%matplotlib notebook Use IPython magic %matplotlib notebook to set the backend to the notebook backend. This will keep the figure alive instead of displaying a static png file and can hence also show animations.
Complete example:
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
plt.show()
%matplotlib tk Use IPython magic %matplotlib tk to set the backend to the tk backend. This will open the figure in a new plotting window, which is interactive and can thus also show animations.
Complete example:
%matplotlib tk
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
plt.show()
Convert animation to mp4 video (option mentionned by #Perfi already):
from IPython.display import HTML
HTML(ani.to_html5_video())
or use plt.rcParams["animation.html"] = "html5" at the beginning of the notebook.
This will require to have ffmpeg video codecs available to convert to HTML5 video. The video is then shown inline. This is therefore compatible with %matplotlib inline backend. Complete example:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["animation.html"] = "html5"
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
ani
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
from IPython.display import HTML
HTML(ani.to_html5_video())
Convert animation to JavaScript:
from IPython.display import HTML
HTML(ani.to_jshtml())
or use plt.rcParams["animation.html"] = "jshtml" at the beginning of the notebook.
This will display the animation as HTML with JavaScript. This highly compatible with most new browsers and also with the %matplotlib inline backend. It is available in matplotlib 2.1 or higher.
Complete example:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["animation.html"] = "jshtml"
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
ani
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
from IPython.display import HTML
HTML(ani.to_jshtml())
You may find this tutorial interesting.
If you can turn what you need into a matplotlib animation, and I'm fairly sure from your description that it's possible, you can then use
from matplotlib import rc, animation
rc('animation', html='html5')
and display your animation using
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=N, interval=20, blit=True)
anim
Might come in handy!
Jupyter widgets is a good way of displaying animations. The code below displays an animated gif.....
from ipywidgets import Image
from IPython import display
animatedGif = "animatedGifs/01-progress.gif" #path relative to your notebook
file = open(animatedGif , "rb")
image = file.read()
progress= Image(
value=image,
format='gif',
width=100,
height=100)
display.display(progress)
You can close this animation using:
progress.close()
N.B. I found a few nice animated gifs from http://www.downgraf.com/inspiration/25-beautiful-loading-bar-design-examples-gif-animated/.
I had a similar problem, and this question helped me get started. I put together a notebook that illustrates using FuncAnimation along with good explanations of why the notebook does some things the way it does. It also has links to instructions on FFmpeg. It also has links to the examples I used in developing and understanding of animations. You can view my contribution at:
Animation Illustration
For your question, you might find interactive sliders a better tool. I also created a notebook which demonstrates interactive widgets in Jupyter. It is available here; however, the interactive parts don't work there.
Both are available in a GitHub Repostory
I tried to program something similar to what the person in this thread programed: Matplotlib Animation
His code does work for me very fine considering the proposed fix but when I tried to program something similar the animation somehow does not work in jupyter notebook for me. (If I download it as a .py it works fine)
I think its very weird that it works as a .py but not in jupyter, especially considering that the code example in the link above also does work in jupyter notebook for me.
My code is the following: (of course there are functions missing which produce the variables "time" and "inputs[b,t,x,y,z]")
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
def plot_fig():
global time, inputs
fig = plt.figure("Animation")
img = []
for i in range(time):
img.append([plt.imshow(inputs[1,i,:,:,0])])
anim = animation.ArtistAnimation(fig, img, interval = 25, blit=True, repeat_delay = 0)
plt.show()
Somehow I only get a static picture of inputs[1,0,:,:,0] in jupyter notebook.
I do not get any errors.
Does anyone have an idea why?
Thanks for any help!
Edit:
this code which creates random matrices does somehow work for me as well.
Very weird considering the inputs matrix in the code above has the right dimensions and the right content.
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
time = 100
fig = plt.figure("Animation")
img = []
for i in range(time):
inputs = np.random.rand(10,10)
img.append([plt.imshow(inputs)])
anim = animation.ArtistAnimation(fig, img, interval = 25, blit=True, repeat_delay = 0)
plt.show()