【问题标题】:matplotlib interactive mode: determine if figure window is still displayedmatplotlib交互模式:判断图形窗口是否仍显示
【发布时间】:2014-10-18 11:31:06
【问题描述】:

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

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

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

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...

我可以使用什么(根据 plt.gca()、fig 等...)来确定是否需要重新绘制?有没有我可以检查的状态?

非常感谢,

大卫

【问题讨论】:

  • 认为问题需要更加清晰。您是否跟踪他们打开的数字?可以同时打开多个图形还是只打开一个图形?

标签: python matplotlib


【解决方案1】:

与 unutbu 的回答一样,您还可以检查给定的图形是否仍然打开

import matplotlib.pyplot as plt

if plt.fignum_exists(<figure number>):
    # Figure is still opened
else:
    # Figure is closed

图的图号在fig.number

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

PPS:也就是说,subplots(…, num=&lt;string num&gt;) 使用给定的 string 数字正确地恢复了现有图形。因此,在 Matplotlib 的某些部分中,数字仍然通过其字符串编号来识别(但 fignum_exists() 不使用此类字符串)。

【讨论】:

  • 请注意,您可以像plt.fignum_exists(fig.number)一样使用fig.number获取号码。
  • 但是,当我通过fig, ax1 = plt.subplots(1, 1) 创建一个图形并且尚未显示它时,plt.fignum_exists(fig.number) 的输出是True。不应该是False吗?
  • 图形不一定要显示才能存在:它本质上是某些图形的内部表示。通常会显示图形,但有时不会显示:一个简单的例子是当图形被创建为 PDF 文件时。因此,即使没有显示任何内容,也可以访问该图形(例如,在任何图形完成之前,可能希望在多个图形之间切换 plt.figure(num=…))。
【解决方案2】:
import matplotlib.pyplot as plt
if plt.get_fignums():
    # window(s) open
else:
    # no windows

【讨论】:

  • matplotlib.pyplot.get_fignums() 在没有额外导入的情况下做了几乎相同的事情。
  • @Avaris:谢谢,这样更好。
猜你喜欢
  • 2014-06-17
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多