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 manipulate figures while a script is running in Python Matplotlib?
Manipulating figures while a script is running allows you to create dynamic, animated plots that update in real-time. This is useful for visualizing data streams, creating interactive demonstrations, or building animated visualizations.
Basic Figure Manipulation
To manipulate figures during script execution, you need to create a figure, display it, and then update it using canvas.draw() and plt.pause() ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create figure and get current axis
fig = plt.figure()
ax = fig.gca()
fig.show()
# Animate by adding random lines
for i in range(10):
ax.plot(np.random.randn(10, 1), linestyle='-')
fig.canvas.draw()
plt.pause(0.1) # Pause for 0.1 seconds
plt.close(fig)
Dynamic Data Visualization
Here's a more practical example showing how to update a plot with changing data ?
import numpy as np
import matplotlib.pyplot as plt
# Create figure and axis
fig, ax = plt.subplots(figsize=(8, 4))
x = np.linspace(0, 2*np.pi, 100)
# Initial empty line plot
line, = ax.plot([], [], 'b-')
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-2, 2)
ax.set_title('Dynamic Sine Wave')
# Animate sine wave with changing frequency
for freq in np.linspace(1, 5, 20):
y = np.sin(freq * x)
line.set_data(x, y)
ax.set_title(f'Sine Wave (frequency = {freq:.1f})')
fig.canvas.draw()
plt.pause(0.2)
plt.show()
Key Methods
| Method | Purpose | Usage |
|---|---|---|
fig.canvas.draw() |
Updates the figure display | Call after modifying plot elements |
plt.pause(time) |
Pauses execution for specified seconds | Controls animation speed |
fig.show() |
Displays the figure | Shows figure without blocking script |
plt.close(fig) |
Closes the figure | Prevents memory leaks |
Real-time Data Update
For continuously updating plots, use this pattern to clear and redraw data ?
import numpy as np
import matplotlib.pyplot as plt
# Setup interactive mode
plt.ion()
fig, ax = plt.subplots()
# Simulate real-time data
for i in range(50):
# Generate new data
x = np.arange(i)
y = np.random.cumsum(np.random.randn(i))
# Clear previous plot and draw new data
ax.clear()
ax.plot(x, y, 'g-', linewidth=2)
ax.set_title(f'Step {i+1}: Real-time Data')
ax.set_xlabel('Time')
ax.set_ylabel('Value')
# Update display
plt.draw()
plt.pause(0.1)
plt.ioff() # Turn off interactive mode
plt.show()
Best Practices
-
Interactive Mode: Use
plt.ion()at the start andplt.ioff()at the end for smoother animations -
Canvas Drawing: Always call
fig.canvas.draw()after modifying plot elements -
Memory Management: Close figures with
plt.close()when done to prevent memory leaks - Pause Duration: Use appropriate pause times − too short may cause flickering, too long makes animation jerky
Conclusion
Dynamic figure manipulation in Matplotlib requires using canvas.draw() to update the display and plt.pause() to control timing. This enables real-time visualizations and animated plots for interactive data exploration.
