5 Best Ways to Close a Python Figure by Keyboard Input Using Matplotlib

πŸ’‘ Problem Formulation: When working with Matplotlib in Python, a common need is to close the graph or figure window with a keyboard command. Developers or users want to move quickly without reaching for the mouse, aiming for a faster and more keyboard-centric workflow. This guide will demonstrate how a figure can be closed using various keyboard inputs.

Method 1: Use the ‘close’ Event with a Specific Key

Matplotlib figures can be programmed to close in response to specific key events. By binding a function to the ‘key_press_event’, developers can designate a certain key (like ‘q’ or ‘escape’) to trigger the closing of a figure.

Here’s an example:

import matplotlib.pyplot as plt

def close_figure(event):
    if event.key == 'q':
        plt.close(event.canvas.figure)

fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', close_figure)
plt.show()

When ‘q’ is pressed, the active figure will close.

This example binds the close_figure function to a key press event within a Matplotlib figure. When the key ‘q’ is pressed, the plt.close() method is called for the figure associated with the canvas where the event was triggered, leading to the figure closing.

Method 2: Set a Global Default Key for Closing Figures

Matplotlib allows configuring a default key in the rcParams to close all figures. This is a more permanent solution, affecting all plots created in the session or script.

Here’s an example:

import matplotlib.pyplot as plt

plt.rcParams['keymap.quit'] = ['ctrl+w', 'cmd+w']
plt.plot([1, 2, 3])
plt.show()

Now, pressing ‘Ctrl+W’ (or ‘Cmd+W’ on a Mac) closes the figure.

This snippet configures the rcParams to recognize ‘Ctrl+W’ or ‘Cmd+W’ as global commands to quit any figure window when pressed. This method is beneficial for consistency across different scripts, saving the time and effort of defining close events for each figure.

Method 3: Embedding a Figure in a Tkinter Window

Embedding Matplotlib figures into a GUI framework like Tkinter allows for the creation of customized keybindings through the GUI’s event system. This method gives more control and potentially additional features within the GUI framework.

Here’s an example:

import tkinter as Tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def on_key_event(event):
    if event.keysym == 'Q':
        root.quit()

root = Tk.Tk()
fig = plt.Figure()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack()

# Bind the 'q' key to the quitting of the window
root.bind('<Q>', on_key_event)
Tk.mainloop()

Pressing ‘Q’ will now terminate the Tkinter window and the embedded Matplotlib figure.

The snippets embed a Matplotlib figure within a Tkinter window and bind a function to the ‘Q’ key press event. When ‘Q’ is pressed, it calls the root.quit() method, closing both the Tkinter application and the Matplotlib figure.

Method 4: Using a Context Manager

Another elegant method is to create a context manager that attaches and removes the binding for closing a figure with a key press, which keeps the code modular and reusable.

Here’s an example:

import matplotlib.pyplot as plt
from contextlib import contextmanager

@contextmanager
def bind_close_key(fig, key='q'):
    def close(event):
        if event.key == key:
            plt.close(fig)

    cid = fig.canvas.mpl_connect('key_press_event', close)
    try:
        yield
    finally:
        fig.canvas.mpl_disconnect(cid)

with bind_close_key(plt.figure()):
    plt.plot([1, 2, 3])
    plt.show()

Within the ‘with’ block, pressing ‘q’ will close the figure.

This code defines a context manager bind_close_key that takes a figure and optional key argument, sets up an event handler for key presses, and closes the figure if the specified key is pressed. After the ‘with’ block, the event is automatically disconnected, keeping the code clean.

Bonus One-Liner Method 5: Use an Anonymous Function

For the shortest way to implement this feature, use a lambda function directly in the mpl_connect call to close the figure.

Here’s an example:

import matplotlib.pyplot as plt
fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', lambda event: plt.close(fig) if event.key == 'q' else None)
plt.plot([3, 1, 4, 1, 5, 9])
plt.show()

Press ‘q’ and the figure closes immediately.

This one-liner binds a lambda function to the ‘key_press_event’ that closes the current figure if ‘q’ is pressed. It’s a quick and minimalistic approach but might be less readable to those unfamiliar with lambda functions.

Summary/Discussion

  • Method 1: Bind a closure function. Strengths: Specific, easy CTRL. Weaknesses: Need to add to each figure.
  • Method 2: Global RCParam binding. Strengths: One-time setup, global effect. Weaknesses: Less flexibility.
  • Method 3: GUI Framework Embedding. Strengths: Custom GUIs, additional functionality. Weaknesses: More complex, larger footprint.
  • Method 4: Context Manager. Strengths: Reusable, clean code management. Weaknesses: Requires more boilerplate.
  • Method 5: Lambda Oneliner. Strengths: Conciseness. Weaknesses: Potentially confusing for beginners.