使用 matplotlib 可视化数据



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

我知道可以用ionset_data在一个维度上制作动画。但是,二维动画(通过 imshow)很有用,我找不到一种简单的方法来做到这一点。

我知道可以使用函数调用进行动画处理,但这对算法开发没有那么有用(因为您不能使用 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> - 它会挂起并禁用将来的动画(在此计算机上)。尽管有这个答案,但调用此动画过程的不同方法不起作用。如何在计算 2D 数据时查看数据?

编辑:此后,我制作了一个名为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 .

最新更新