使用matplotlib可视化数据

时间:2014-04-06 00:04:34

标签: python matlab animation matplotlib

在Matlab中,您可以使用drawnow查看正在进行的计算结果。我在Python中尝试了类似的语法,包括matplotlib和mayavi。

我知道ionset_data可以animate in one dimension。但是,在两个维度(通过imshow)制作动画很有用,我找不到 easy 方法来做到这一点。

我知道有可能animate using a function call但这对算法开发没有用(因为你不能使用IPython的%run并查询你的程序)。

在matplotlib中,我可以使用

N = 16
first_image = arange(N*N).reshape(N,N)
myobj = imshow(first_image)
for i in arange(N*N):
    first_image.flat[i] = 0
    myobj.set_data(first_image)
    draw()

为图像设置动画,但此脚本不响应<Cntrl-C> - 它会挂起并禁用未来的动画(在此计算机上)。尽管this SO answer,但调用此动画过程的不同方法不起作用。如何在计算2D数据时查看它?

1 个答案:

答案 0 :(得分:1)

编辑:我已经制作了一个名为python-drawnow的软件包来实现以下答案。

您只想从一些复杂的计算中可视化数据而不能平滑地为图像设置动画,是否正确?然后你可以定义一些简单的函数:

def drawnow(draw_fig, wait_secs=1):
    """
        draw_fig: (callable, no args by use of python's global scope) your
        function to draw the figure. it should include the figure() call --
        just like you'd normally do it.  However, you must leave out the
        show().

        wait_secs : optional, how many seconds to wait. note that if this is 0
        and your computation is fast, you don't really see the plot update.

        does not work in ipy-qt. only works in the ipython shell.
    """
    close()
    draw_fig()
    draw()
    time.sleep(wait_secs)

def drawnow_init():
    ion()

这方面的一个例子:

def draw_fig():
    figure()
    imshow(z, interpolation='nearest')
    #show()

N = 16
x = linspace(-1, 1, num=N)
x, y = meshgrid(x, x)
z = x**2 + y**2


drawnow_init()
for i in arange(2*N):
    z.flat[i] = 0
    drawnow(draw_fig)

请注意,这要求您正在绘制的变量是全局变量。这不应该是一个问题,因为您想要可视化的变量似乎是全局的。

此方法对cntrl-c反应良好,即使在快速计算过程中也可见(通过wait_secs

相关问题