Skip to main content
 首页 » 编程设计

python之使用 matplotlib 可视化数据

2025年05月04日6lyj

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

我知道有可能 animate in one dimension与 ion和 set_data .但是,二维动画(通过 imshow)很有用,我找不到简单的方法来做到这一点。

我知道有可能 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> -- 它挂起并禁用 future 的动画(在这台机器上)。尽管this SO answer , 调用此动画过程的不同方式不起作用。如何在计算时查看二维数据?

请您参考如下方法:

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