Brent
Brent

Reputation: 729

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?

Upvotes: 8

Views: 29436

Answers (3)

Tjaart
Tjaart

Reputation: 496

You can you use the Toplevel() widget from the tkinter library together with the matplotlib backend.

Here is a full example:

from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

fig,(ax) = plt.subplots()
x = np.linspace(0, 2 * np.pi)
y = np.transpose([np.sin(x)])
ax.plot(y)

graph = Toplevel()
canvas = FigureCanvasTkAgg(fig,master=graph)
canvas.get_tk_widget().grid()
canvas.show()

import pdb; pdb.set_trace()

Calling:

graph.withdraw()

will hide the plot, and:

graph.deiconify()

will display it again.

Upvotes: 2

Sameer
Sameer

Reputation: 2505

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

Upvotes: 8

jdmcbr
jdmcbr

Reputation: 6406

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.

Upvotes: 2

Related Questions