代码之家  ›  专栏  ›  技术社区  ›  Bananach

matplotlib以我希望的方式工作

  •  0
  • Bananach  · 技术社区  · 7 年前

    我不明白用matplotlib创建的图形是如何显示的,何时更新,何时阻塞等等。

    为了帮助我理解并帮助我让matplotlib做我特别需要的事情,有人能帮我创建一个 matplotlib.figure 包装器/几乎克隆,让我们称之为MyFigure,其行为完全如下面代码(及其注释)所述?

    X=[0,1]
    Y=[0,1]
    Y2a=[0,2]
    Y2b=[0,2.5]
    Y3a=[0,3]
    Y3b=[0,3.5]
    Y4=[0,4]
    
    fig = MyFigure() # Nothing happens
    ax=fig.gca() # Nothing happens
    ax.plot(X,Y) # Nothing happens
    fig.show() # New window (1) appears and shows plot of X,Y; execution continues directly
    ax.set_xlabel('X') # Window 1 gets X axis label
    ax.set_ylabel('Y') # Window 1 gets Y axis label
    fig.hide() # Window 1 disappears
    time.sleep(10) # No open windows for 10 seconds 
    fig.show() # Window 1 reappears and looks the same as before
    
    fig2 = MyFigure() # Nothing happens
    fig2.show() # New window (2) appears and is empty
    ax2 = fig2.gca() # Window 2 shows axes
    ax2.plot(X,Y2a) # Window 2 shows X,Y2a
    fig2.show() # Nothing happens, could be omitted
    time.sleep(60) # Long computation. In the meantime, windows 1 and 2 can still be resized and their controls (zoom etc.) can be used
    ax2.plot(X,Y2b) # Window 2 shows X,Y2a as well as X,Y2b
    fig2.hide() # Window 2 disappears
    
    fig3 = MyFigure() # Nothing happens
    ax3 = fig3.gca() # Nothing happens
    ax3.plot(X,Y3a) # Nothing happens 
    fig3.show() # Window 3 appears and shows plot of X,Y3a; execution continues
    fig3.freeze() # Nothing happens, Window 3 is still open and can be manipulated
    ax3.set_xlabel('X') # Nothing happens
    ax3.set_ylabel('Y') # Nothing happens
    fig3.thaw() # Window 3 gets X and Y axis labels 
    fig3.clear() # Window 3 is still open but empty
    ax3 = fig3.gca() # Window 3 shows empty axes
    ax3.plot(X,Y3b) # Window 3 shows plot of X,Y3b
    
    fig4 = MyFigure() # Nothing happens 
    ax4 = fig4.gca() # Nothing happens 
    ax4.plot(X,Y4) # Nothing happens
    fig4.show(block=True) # Window 4 opens and shows X,Y4. Execution pauses 
    print('Window 4 was closed by user') # Happens after user closes window 4
    fig4.show() # Window 4 reappears and looks as before
    fig4.close() # Window 4 disappears and its resources are freed
    try:
       fig4.show()
    except Exception:
       print('Something went wrong') # Prints 'Something went wrong'
    
    # Windows 1,2,3 still "exist". 
    # Window 2 is not visible but could be manipulated and shown again in later code.
    # Windows 1 and 3 are still visible and can be manipulated by the user. 
    # They disappear as soon as the objects fig and fig3 are garbage collected, 
    # or their `hide` or `close` methods are called.
    

    请注意,调用 MyFigure().show() 你可以做任何你需要的事情为了让事情像我描述的那样运转,我只是用了这个词 show 因为它和什么相似 plt.show 已经有了。 我听说至少有三种方法可以帮助我实现一些关于交互性的想法( plt.ion() fig.show(block=False) , plt.draw() ipython (我不打算使用的)但是,这些命令都没有像我希望的那样工作,我也不太理解它们背后的逻辑模型。请看问题的底部,了解我失败的尝试。

    我不想讨论或批评默认情况下matplotlib图形及其方法的工作方式。我确信它们的工作方式有很好的技术和功能上的原因,但它与我的直觉(从其他地方没有真正的GUI经验中得到的)不兼容,而且在学习简单绘图命令之外的任何东西之前,每当我不得不使用它时,我都会对它感到沮丧。我希望改变这一点。

    基本上,我想 MyFigure 实例表示具有两个重要布尔实例变量的线程: visible 和 frozen show() 和 hide() ; 第二个选项控制更改(例如新打印)是立即添加到绘图区域还是添加到队列,并且可以通过 freeze() 和 thaw() .

    show(block=False) 将仅在用户(或具有MyFigure实例访问权限的另一个线程)关闭相应窗口后返回。无论当前值是多少,都可以调用它 并将导致 visible=False . 电话 将设置 frozen=False 并将更改队列应用于图形(即使在 ,但在该状态下冻结和解冻图形没有意义,除非同时在另一个线程中操纵该图形)。

    对我来说最重要的是 show() 实例的交互行为;我主要描述了 freeze 预期在我的设置中如何处理该用例的问题的行为。我不喜欢这个 ax=fig.gca() fig.add(matplotlib.Axes()) 但这与这个问题无关(此外,我相信我自己能解决这个问题)。


    为了澄清我的挣扎,让我记录下我迄今为止失败的尝试:

    plt.ion()

    我用

    def MyFigure(): 
        plt.ion()
        return plt.figure()
    

    我把第一块注释掉,然后继续 fig2 = ... . time.sleep(60) ,60秒内没有打开的窗口。

    图显示(块=假)

    plt.draw()

    draw 作为方法的一个实例 fig 导致 TypeError: draw_wrapper() missing 1 required positional argument: 'renderer' .

    暂时忽略这个问题,, plt.draw() 它本身没有任何作用。根据一些互联网研究,我发现 plt.pause(0.01) fig.hide() )如果我全部替换 fig.show() plt.draw();plt.pause(0.01) ,但它似乎超越了丑陋,也不像互联网推荐的那样。


    (对于潜在的亲密投票者:我可以为代码中的每一行提出一些具体的问题。但是,我觉得所有期望的行为(a)都足够相关,可以一起呈现(b)最好以代码的形式描述,希望将代码与我希望没有的注释一起写。)

    2 回复  |  直到 7 年前
        1
  •  2
  •   cvanelteren    7 年前

    老实说,我对网络上的matplotlib教程及其在实践中的使用感到失望。就我个人而言,当我开始以面向对象的方式使用matplotlib时,许多matplotlib的挫折感消失了。而不是做:

    from matplotlib.pyplot import *
    fig = figure() # implicitly create axis
    ax  = gca() 
    

    做:

    fig, ax = subplots() # explicitly create figure and axis
    

    draw()
    show()
    fig.canvas.draw()
    fig.show()
    

    通过这种方式,您可以显式保留特定地物,而不是依赖matplotlib当前聚焦的地物。这个 ion

        2
  •  1
  •   ImportanceOfBeingErnest    7 年前

    也许以下就是你想要的。由于这个问题非常广泛,同时要求很多东西,我将仅限于前两个例子。这里的关键是使用 plt.ion()

    import matplotlib
    matplotlib.use("Qt5Agg")
    import matplotlib.pyplot as plt
    
    
    X=[0,1]
    Y=[0,1]
    Y2a=[0,2]
    Y2b=[0,2.5]
    Y3a=[0,3]
    Y3b=[0,3.5]
    Y4=[0,4]
    
    plt.ion()
    
    fig, ax  = plt.subplots() # Nothing happens
    ax.plot(X,Y) # Nothing happens
    plt.draw()
    plt.pause(.1) # New window (1) appears and shows plot of X,Y; execution continues directly
    ax.set_xlabel('X') # Window 1 gets X axis label
    ax.set_ylabel('Y') # Window 1 gets Y axis label
    figManager = plt.get_current_fig_manager()
    figManager.window.showMinimized() # Window 1 disappears
    plt.pause(10) # No open windows for 10 seconds 
    figManager.window.showNormal() # Window 1 reappears and looks the same as before
    
    
    fig2 = plt.figure() # Nothing happens
    fig2.show() # New window (2) appears and is empty
    ax2 = fig2.gca() # Window 2 shows axes
    ax2.plot(X,Y2a) # Window 2 shows X,Y2a
    pass # Nothing happens, could be omitted
    for i in range(60*2):
        plt.pause(1/2) # Long computation. In the meantime, windows 1 and 2 can still be resized and their controls (zoom etc.) can be used
    ax2.plot(X,Y2b) # Window 2 shows X,Y2a as well as X,Y2b
    figManager = plt.get_current_fig_manager()
    figManager.window.showMinimized() # Window 2 disappears
    

    • (1) plt.ion在这里做什么?
      打开交互模式。这意味着可以在GUI中绘制图形,而无需启动GUI事件循环。其优点显然是GUI事件循环不会阻塞后续代码;缺点是您没有事件循环-因此GUI可能很快变得无响应,您自己负责让它管理事件。这是什么 plt.pause 在这种情况下没有。可能发生的情况是,无论您使用什么来运行脚本,都已经为您打开了交互模式。在这种情况下,请使用 plt.ioff() 看看有什么不同。

    • (2) 像plt.pause这样的东西能在不抓住焦点的情况下实现吗?
      可能吧,但大多数用户都希望在绘制时看到自己的绘图。所以它不是以这种方式实现的。

    • (3) 如果没有plt.pause(.1),plt.draw没有任何效果,为什么它以当前形式存在?
      plt.draw() 绘制图形。这在各种情况下都很有用,完全独立于 ion


    • (5) 在进行实际计算时(与plt.pause相反),是否真的不可能使数字响应?
      不可以。您可以在事件循环中运行计算。您还可以在线程中运行它。最后你可以打电话 plt.pause() 或 fig.canvas.flush_events() 在计算过程中重复。

    • (6) figManager.window.showMinimized 对我没有任何影响;这是因为它依赖于操作系统吗?
      它不应该依赖于操作系统。但它肯定依赖于后端。这就是我将后端设置在代码顶部的原因。