如何切换 matplotlib 图形的可见性?

Bre*_*ent 7 python matplotlib

有没有办法让 matplotlib 图形消失并重新出现以响应某些事件?(即按键)

我试过使用,fig.set_visible(False)但这似乎对我没有任何作用。

简单的代码示例:

import matplotlib
import matplotlib.pyplot as plt

fig=matplotlib.pyplot.figure(figsize=(10, 10))

# Some other code will go here

def toggle_plot():
  # This function is called by a keypress to hide/show the figure
  fig.set_visible(not fig.get_visible()) # This doesn't work for me

plt.show()
Run Code Online (Sandbox Code Playgroud)

我尝试这样做的原因是因为我在图中运行了一堆绘图/动画,它们显示了正在运行的模拟的输出,但是一直显示它们会大大降低我的计算机的速度。有任何想法吗?

Sam*_*eer 8

您必须调用plt.draw()以实际实例化任何更改。这应该有效:

def toggle_plot():
  # This function is called by a keypress to hide/show the figure
  fig.set_visible(not fig.get_visible())
  plt.draw()
Run Code Online (Sandbox Code Playgroud)

  • 我测试并确认它只隐藏图形窗口的内容而不是窗口本身。 (2认同)