通过 Matplotlib 中的 OO 接口获取图形管理器

ale*_*lov 7 matplotlib figure

我希望能够获得创建的图形的 figure_manager:例如,我可以使用 pyplot 界面使用:

from pylab import*
figure()    
plot(arange(100))
mngr = get_current_fig_manager()
Run Code Online (Sandbox Code Playgroud)

但是,如果我有几个数字怎么办:

from pylab import *
fig0 = figure()
fig1 = figure()    
plot(arange(100))
mngr = fig0.get_manager() #DOES NOT WORK - no such method as Figure.get_manager()
Run Code Online (Sandbox Code Playgroud)

但是,仔细搜索图形 API http://matplotlib.org/api/figure_api.html并没有用。我的 IDE 中的图形实例也没有自动完成,似乎没有任何方法/成员给我一个“管理器”。

那么我该如何做到这一点,一般来说,如果有一个 pyplot 方法,我需要在 OO 界面中使用它的模拟方法,我应该在哪里查看?

PS:无论如何,get_current_fig_manager() 返回什么样的对象?在调试器中,我得到:

type(get_current_fig_manager())
<type 'instance'>
Run Code Online (Sandbox Code Playgroud)

这听起来很神秘......

pel*_*son 6

好问题。你的权利,文档没有说任何关于能够获得经理或画布的内容。根据代码的经验,您的问题的答案是:

>>> import matplotlib.pyplot as plt
>>> a = plt.figure()
>>> b = plt.figure()

>>> a.canvas.manager
<matplotlib.backends.backend_tkagg.FigureManagerTkAgg instance at 0x1c3e170>
>>> b.canvas.manager
<matplotlib.backends.backend_tkagg.FigureManagerTkAgg instance at 0x1c42ef0>
Run Code Online (Sandbox Code Playgroud)

了解这些东西的最好地方是阅读代码。在这种情况下,我知道我想要获取画布以便我可以抓住图形管理器,所以我查看了 set_canvas 方法figure.py,发现以下代码:

def set_canvas(self, canvas):
    """
    Set the canvas the contains the figure

    ACCEPTS: a FigureCanvas instance
    """
    self.canvas = canvas
Run Code Online (Sandbox Code Playgroud)

从那里开始(因为没有 get_canvas 方法),我知道画布的存储位置并且可以直接访问它。

HTH