Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to close a Python figure by keyboard input using Matplotlib?
To close a Python figure by keyboard input, we can use plt.pause() method, an input prompt, and close() method. This approach allows interactive control over when the figure window closes.
Steps
- Set the figure size and adjust the padding between and around the subplots
- Create random data points using NumPy
- Create a new figure using
figure()method - Plot the data points using
plot()method - Set the title of the plot
- Redraw the current figure using
draw()method - Use
pause()to display the figure briefly - Take input from the user to proceed to the next statement
- Use
close()method to close the figure
Example
Here's how to create a plot that waits for keyboard input before closing ?
import numpy as np
from matplotlib import pyplot as plt
# Set figure configuration
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data points
t = np.arange(0.0, 2.0, 0.01)
y = np.exp(-t)
# Create and plot the figure
fig = plt.figure()
plt.plot(t, y, lw=5, color='red')
plt.title("$y=e^{-t}$")
# Display the plot and wait for user input
plt.draw()
plt.pause(1)
input("Press Enter to close the figure...")
plt.close(fig)
How It Works
The plt.draw() method renders the figure, while plt.pause(1) displays it for 1 second. The input() function pauses execution until the user presses Enter, giving them control over when to close the figure window.
Alternative Approach Using Event Handling
For more advanced control, you can use matplotlib's event handling ?
import numpy as np
import matplotlib.pyplot as plt
def on_key(event):
if event.key == 'q':
plt.close()
# Create data and plot
t = np.arange(0.0, 2.0, 0.01)
y = np.exp(-t)
fig, ax = plt.subplots()
ax.plot(t, y, lw=5, color='red')
ax.set_title("Press 'q' to quit")
# Connect the key press event
fig.canvas.mpl_connect('key_press_event', on_key)
plt.show()
Output
Conclusion
Use input() with plt.pause() for simple keyboard-controlled figure closing. For more advanced interactions, implement event handlers that respond to specific key presses like 'q' to quit.
