Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle visibility of matplotlib figures?

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?

like image 315
Brent Avatar asked Feb 11 '15 20:02

Brent


People also ask

How do I hide a figure from being shown in matplotlib?

set_visible(False) (as seen in this answer).

How do I hide a plot in matplotlib?

Plot x and y points using the plot() method with linestyle, labels. To hide the grid, use plt. grid(False).


2 Answers

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()
like image 162
Sameer Avatar answered Nov 03 '22 22:11

Sameer


There is a small guide to image toggling in the matplotlib gallery. I was able to use set_visible and get_visible() as shown in the example. The calls in the matplotlib gallery example are on AxesImage instances, rather than Figure instances, as in your example code. That is my guess as to why it did not work for you.

like image 41
jdmcbr Avatar answered Nov 03 '22 22:11

jdmcbr