Python – How to toggle visibility of matplotlib figures

matplotlibpython

Is there a way that I can make a matplotlib figure disappear and reappear in response to some event? (i.e. a keypress)

I've tried using fig.set_visible(False) but that doesn't seem to do anything for me.

Simple example of code:

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()

The reason I'm trying to do this is because I have a bunch of plots/animations running on the figure that show the output of a running simulation, but displaying them all the time slows down my computer a lot.
Any ideas?

Best Solution

You have to call plt.draw() to actually instantiate any changes. This should work:

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