matplotlib交互模式:确定是否仍然显示数字窗口

Dav*_*ave 16 python matplotlib

我在交互模式下使用matplotlib向用户显示一个帮助他们输入一系列变量的图.他们可以选择点击"?" 显示此图,然后将重复提示变量.

如果它仍在显示,我怎么知道不重新绘制这个图?

从表面上看,我有这个笨重的(伪ish)代码:

answer = None
done_plot = False
while answer == None:
    answer = get_answer()
    if answer == '?':
        if done_plot:
            have_closed = True
            ##user's already requested a plot - has s/he closed it?
            ## some check here needed:
            have_closed = ?????

            if have_closed == False:
                print 'You already have the plot on display, will not re-draw'
                answer = None
                continue
        plt.ion()
        fig = plt.figure()
        ### plotting stuff
        done_plot = True
        answer = None
    else:
        ###have an answer from the user...
Run Code Online (Sandbox Code Playgroud)

我可以使用什么(根据plt.gca(),无花果等...)来确定我是否需要重新绘制?我可以检查某个地方的状态吗?

非常感谢,

大卫

Eri*_*got 24

与unutbu的答案一样,你也可以检查一个给定的数字是否仍然打开

import matplotlib.pyplot as plt

if plt.fignum_exists(<figure number>):
    # Figure is still opened
else:
    # Figure is closed
Run Code Online (Sandbox Code Playgroud)

图中的图号是fig.number.

PS:请注意,"number" figure(num=…)实际上可以是一个字符串:它显示在窗口标题中.但是,该图仍然具有number数字属性:原始字符串num值不能与之一起使用fignum_exists().

PPS:也就是说,subplots(…, num=<string num>)用给定的字符串编号正确地恢复现有的数字.因此,数字在Matplotlib的某些部分仍以其字符串编号为人所知(但fignum_exists()不使用此类字符串).

  • 只需注意,您可以使用`fig.number`获取数字,例如`plt.fignum_exists(fig.number)`. (3认同)

unu*_*tbu 10

import matplotlib.pyplot as plt
if plt.get_fignums():
    # window(s) open
else:
    # no windows
Run Code Online (Sandbox Code Playgroud)

  • `matplotlib.pyplot.get_fignums()`在没有额外导入的情况下几乎完全相同. (2认同)