tutorial graficar funcanimation examples animaciones python animation matplotlib jupyter-notebook ipython-notebook

python - graficar - Animaciones en línea en Jupyter



matplotlib animation python 3 (3)

backend portátil

''En línea'' significa que los gráficos se muestran como gráficos png. Esas imágenes png no pueden ser animadas . Mientras que en principio uno podría construir una animación reemplazando sucesivamente las imágenes png, esto probablemente no sea deseado.

Una solución es utilizar el backend del portátil, que es totalmente compatible con FuncAnimation ya que representa la figura matplotlib en sí:

%matplotlib notebook

jsanimacion

A partir de matplotlib 2.1, podemos crear una animación utilizando JavaScript. Esto es similar a la solución ani.to_html5() , excepto que no requiere ningún ani.to_html5() video.

from IPython.display import HTML HTML(ani.to_jshtml())

Un ejemplo completo:

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() ax.axis([0,2*np.pi,-1,1]) l, = ax.plot([],[]) def animate(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())

Alternativamente, haga que jsanimation sea el valor predeterminado para mostrar animaciones,

plt.rcParams["animation.html"] = "jshtml"

Luego, al final simplemente ani para obtener la animación.

También vea esta respuesta para una descripción completa.

Tengo un script de animación en python (que utiliza la función de animación de matplotlib), que se ejecuta en Spyder pero no en Jupyter. He intentado seguir varias sugerencias, como agregar "% matplotlib en línea" y cambiar el backend de matplotlib a "Qt4agg", todo sin éxito. También he intentado ejecutar varias animaciones de ejemplo (de los tutoriales de Jupyter), ninguna de las cuales ha funcionado. A veces recibo un mensaje de error y otras veces aparece la trama, pero no se anima. Por cierto, he conseguido que pyplot.plot () funcione con "% matplotlib inline".

¿Alguien sabe de un portátil Jupyter con un ejemplo de animación en línea SIMPLE que use funcAnimation? Gracias de antemano por la ayuda!

[Nota: estoy en Windows 7]


Aquí está la respuesta que reuní de varias fuentes, incluidos los ejemplos oficiales. He probado con las últimas versiones de Jupyter y Python.

import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import HTML #========================================= # Create Fake Images using Numpy # You don''t need this in your code as you have your own imageList. # This is used as an example. imageList = [] x = np.linspace(0, 2 * np.pi, 120) y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1) for i in range(60): x += np.pi / 15. y += np.pi / 20. imageList.append(np.sin(x) + np.cos(y)) #========================================= # Animate Fake Images (in Jupyter) def getImageFromList(x): return imageList[x] fig = plt.figure(figsize=(10, 10)) ims = [] for i in range(len(imageList)): im = plt.imshow(getImageFromList(i), animated=True) ims.append([im]) ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000) plt.close() # Show the animation HTML(ani.to_html5_video()) #========================================= # Save animation as video (if required) # ani.save(''dynamic_images.mp4'')


Hay un ejemplo sencillo dentro de este tutorial aquí: http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/

Para resumir el tutorial anterior, básicamente necesitas algo como esto:

from matplotlib import animation from IPython.display import HTML # <insert animation setup code here> anim = animation.FuncAnimation() # With arguments of course! HTML(anim.to_html5_video())

Sin embargo...

Tuve muchos problemas para hacer que eso funcionara. Esencialmente, el problema fue que los usos anteriores (de manera predeterminada) ffmpeg y el códec x264 en el fondo, pero estos no estaban configurados correctamente en mi máquina. La solución fue desinstalarlos y reconstruirlos desde la fuente con la configuración correcta. Para obtener más detalles, vea la pregunta que le hice con una respuesta de trabajo de Andrew Heusser: Animaciones en el portátil ipython (jupyter) - ValueError: operación de E / S en un archivo cerrado

Entonces, intente to_html5_video solución to_html5_video que se encuentra arriba, y si no funciona, intente también la desinstalación / reconstrucción de ffmpeg y x264 .