【问题标题】:Visualizing data with matplotlib使用 matplotlib 可视化数据
【发布时间】:2014-04-06 00:04:33
【问题描述】:

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

我知道animate in one dimensionionset_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> - 它挂起并禁用未来的动画(在这台机器上)。尽管this SO answer,调用此动画过程的不同方式不起作用。如何查看正在计算的 2D 数据?

【问题讨论】:

    标签: python matlab animation matplotlib


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2015-09-23
      • 1970-01-01
      • 2016-09-10
      • 2011-07-04
      • 2018-07-16
      • 2017-09-14
      • 2021-11-04
      • 2020-09-14
      • 2022-01-03
      相关资源
      最近更新 更多