在ipython笔记本中的动画图形

问题描述 投票:18回答:8

有没有办法创建动画图形。例如,显示具有不同参数的相同图表。

例如是SAGE笔记本,可以写:

a = animate([circle((i,i), 1-1/(i+1), hue=i/10) for i in srange(0,2,0.2)], 
            xmin=0,ymin=0,xmax=2,ymax=2,figsize=[2,2])
a.show()
plot ipython
8个回答
7
投票

更新:2014年1月

Jake Vanderplas为matplotlib动画创建了一个基于Javascript的包,可用here。使用它很简单:

 # https://github.com/jakevdp/JSAnimation
 from JSAnimation import examples
 examples.basic_animation()

有关更完整的说明和示例,请参阅his blog post。历史答案(见枪支纠正)

是的,Javascript更新还没有正确保存图像框架,所以有闪烁,但你可以使用这种技术做一些非常简单的事情:

import time, sys
from IPython.display import clear_output
f, ax = plt.subplots()

for i in range(10):
  y = i/10*sin(x) 
  ax.plot(x,y)
  time.sleep(0.5)
  clear_output()
  display(f)
  ax.cla() # turn this off if you'd like to "build up" plots
plt.close()

9
投票

这有可怕的闪烁,但至少这创造了一个动画为我的情节。它基于Aron,但是Aron不能按原样运行。

import time, sys
from IPython.core.display import clear_output
f, ax = plt.subplots()

n = 30
x = array([i/10.0 for i in range(n)])
y = array([sin(i) for i in x])
for i in range(5,n):
  ax.plot(x[:i],y[:i])
  time.sleep(0.1)
  clear_output()
  display(f)
  ax.cla() # turn this off if you'd like to "build up" plots
plt.close()

5
投票

如果你使用IPython笔记本,v2.0及以上版本支持interactive widgets。你可以找到一个很好的例子笔记本here(n.b.你需要下载并从你自己的机器上运行才能看到滑块)。

它基本上归结为导入interact,然后传递一个函数,以及参数的范围。例如,从第二个链接:

In [8]:
def pltsin(f, a):
    plot(x,a*sin(2*pi*x*f))
    ylim(-10,10)
In [9]:
interact(pltsin, f=(1,10,0.1), a=(1,10,1));

这将产生一个带有两个滑块的图,用于fa


5
投票

IPython widgets允许您使用Notebook中的GUI对象操作内核中的Python对象。你可能也喜欢Sage hosted IPython Notebooks。在笔记本中共享小部件或交互性可能遇到的一个问题是,如果其他人没有IPython,他们将无法运行您的工作。要解决这个问题,您可以使用Domino将share Notebooks与其他人可以运行的小部件一起使用。

下面是三个可以在Notebook中构建的小部件示例,它们使用pandas过滤数据,分形和3D绘图的滑块。了解更多信息并查看代码和笔记本here

如果您想要实时传输数据或设置模拟以循环运行,您还可以将stream data转换为Notebook中的绘图。免责声明:我为Plotly工作。


1
投票

bqplot现在是一个非常好的选择。它专门为笔记本中的python构建了动画

https://github.com/bloomberg/bqplot


1
投票

如果你想要3D散点图动画,Ipyvolume Jupyter小部件非常令人印象深刻。 http://ipyvolume.readthedocs.io/en/latest/animation.html#


0
投票

在@gugger关于'可怕的闪烁'的评论中,我发现调用clear_output(wait = True)解决了我的问题。该标志告诉clear_output等待渲染,直到它有新的东西呈现。


0
投票

matplotlib有一个animation模块来做到这一点。但是,网站上提供的示例将不会像笔记本中那样运行;你需要做一些调整才能使它工作。

以下是修改为在笔记本中工作的页面示例(粗体修改)。


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import rc
from IPython.display import HTML

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro', animated=True)

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
rc('animation', html='html5')
ani
# plt.show() # not needed anymore

请注意,笔记本中的动画是通过电影制作的,您需要安装ffmpeg并配置matplotlib才能使用它。

© www.soinside.com 2019 - 2024. All rights reserved.