matplotlib Jupyter中的内联动画

f2uvfpb9  于 2022-12-30  发布在  其他
关注(0)|答案(6)|浏览(184)

我有一个python动画脚本(使用matplotlib的funcAnimation),它可以在Spyder中运行,但不能在Jupyter中运行。我尝试了各种建议,如添加“%matplotlib inline”和将matplotlib后端更改为“Qt4agg”,都没有成功。我还尝试运行了几个示例动画(来自Jupyter教程),这些都没有起作用。有时我会收到错误信息,有时情节会出现,但没有动画。顺便说一句,我已经让pyplot.plot()使用“%matplotlib inline”来工作了。
有没有人知道一个工作的Jupyter笔记本与一个简单的内联动画的例子,使用funcAnimation。
[Note:我使用的是Windows 7]

8mmmxcuj

8mmmxcuj1#

笔记本后端

“内联”表示图显示为png图形。这些png图像不能动画化。虽然原则上可以通过连续替换png图像来创建动画,但这可能是不希望的。
一个解决方案是使用笔记本后端,它与FuncAnimation完全兼容,因为它可以呈现matplotlib图形本身:

%matplotlib notebook

js动画

从matplotlib 2.1开始,我们可以使用JavaScript创建动画,这类似于ani.to_html5()解决方案,只是它不需要任何视频编解码器。

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

一些完整的例子:

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())

或者,将jsanimation设为显示动画的默认值,

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

然后在最后简单地声明ani以获得动画。
另请参见this answer以获得完整概述。

xwbd5t1u

xwbd5t1u2#

本教程中有一个简单的示例:http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/
总结一下上面的教程,你基本上需要这样的东西:

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())

然而

我遇到了很多麻烦。本质上,问题是上面的使用(默认)ffmpegx264编解码器在后台,但这些没有在我的机器上正确配置。解决方案是卸载它们,并重建他们从源代码与正确的配置。有关更多细节,请参阅我问的问题与Andrew Heusser的工作答案:ipython(jupyter)笔记本中的动画-值错误:关闭文件上的I/O操作
所以,首先尝试上面的to_html5_video解决方案,如果它不起作用,那么也可以尝试卸载/重建ffmpegx264

vltsax25

vltsax253#

另一种选择:

import matplotlib.animation
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["animation.html"] = "jshtml"
plt.rcParams['figure.dpi'] = 150  
plt.ioff()
fig, ax = plt.subplots()

x= np.linspace(0,10,100)
def animate(t):
    plt.cla()
    plt.plot(x-t,x)
    plt.xlim(0,10)

matplotlib.animation.FuncAnimation(fig, animate, frames=10)

e5nqia27

e5nqia274#

以下是我从多个来源收集到的答案,包括官方示例。我用最新版本的Jupyter和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')
dgtucam1

dgtucam15#

如果您有一个图像列表,并希望通过它们设置动画,则可以使用类似下面的命令:

from keras.preprocessing.image import load_img, img_to_array
from matplotlib import animation
from IPython.display import HTML
import glob

%matplotlib inline

def plot_images(img_list):
  def init():
    img.set_data(img_list[0])
    return (img,)

  def animate(i):
    img.set_data(img_list[i])
    return (img,)

  fig = figure()
  ax = fig.gca()
  img = ax.imshow(img_list[0])
  anim = animation.FuncAnimation(fig, animate, init_func=init,
                                 frames=len(img_list), interval=20, blit=True)
  return anim

imgs = [img_to_array(load_img(i)) for i in glob.glob('*.jpg')]

HTML(plot_images(imgs).to_html5_video())
tuwxkamq

tuwxkamq6#

感谢Kolibril。我终于可以在Jupyter和Google Colab上运行动画了。我修改了一些代码,将生成绘制随机线的动画。

import matplotlib.animation
import matplotlib.pyplot as plt
from itertools import count
import random

plt.rcParams["animation.html"] = "jshtml"
plt.rcParams['figure.dpi'] = 150  

fig, ax = plt.subplots()
x_value = []
y_value = []
index = count();
def animate(t):
    x_value.append(next(index))
    y_value.append(random.randint(0,10))
    ax.cla()
    ax.plot(x_value,y_value)
    ax.set_xlim(0,10)

matplotlib.animation.FuncAnimation(fig, animate, frames=10, interval = 500)

enter image description here

相关问题