Python 使用matplotlib可视化数据

Python 使用matplotlib可视化数据,python,matlab,animation,matplotlib,Python,Matlab,Animation,Matplotlib,在Matlab中,可以使用查看正在进行的计算结果。我在Python中尝试过类似的语法,包括matplotlib和mayavi 我知道可以使用ion和设置数据。然而,在二维动画(通过imshow)是有用的,我找不到一个简单的方法来做到这一点 我知道这是可能的,但这对算法开发没有多大用处(因为你不能使用IPython的%run来查询你的程序) 在matplotlib中,我可以使用 N = 16 first_image = arange(N*N).reshape(N,N) myobj = imshow

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

我知道可以使用
ion
设置数据。然而,在二维动画(通过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()

为图像设置动画,但此脚本不响应
——它将挂起并禁用未来的动画(在此计算机上)。尽管如此,调用此动画过程的不同方法仍然不起作用。如何查看正在计算的二维数据?

编辑:我已经制作了一个名为的包来实现以下答案

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

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