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
Interactive plotting with Python Matplotlib via command line
Interactive plotting in Matplotlib allows you to modify plots dynamically and see changes in real-time. Using plt.ion() and plt.ioff(), you can enable or disable interactive mode to control when plot updates are displayed.
Setting Up Interactive Mode
First, you need to activate the matplotlib backend and enable interactive mode. Open IPython shell and enter the following commands ?
%matplotlib auto import matplotlib.pyplot as plt plt.ion() # Enable interactive mode
Creating an Interactive Plot
Let's create a figure and demonstrate how interactive plotting works ?
# Create figure and axis
fig, ax = plt.subplots() # Plot window will appear
# Draw initial line
line, = ax.plot(range(5), 'b-', linewidth=2)
# Interactive changes - these will update immediately
line.set_color("orange") # Line turns orange
line.set_linewidth(3) # Line becomes thicker
ax.set_title("Interactive Plot") # Add title
Controlling Interactive Mode
You can toggle interactive mode on and off during your session ?
# Turn off interactive mode
plt.ioff()
# Changes won't appear immediately
line.set_color("red")
line.set_linestyle("--")
# You need to manually update
plt.draw() # Force update when interactive mode is off
# Turn interactive mode back on
plt.ion()
# Now changes appear immediately again
line.set_color("green")
ax.set_ylabel("Values")
Key Interactive Functions
| Function | Purpose | Effect |
|---|---|---|
plt.ion() |
Enable interactive mode | Plot updates automatically |
plt.ioff() |
Disable interactive mode | Plot updates manually only |
plt.draw() |
Force plot update | Updates plot when interactive mode is off |
plt.show() |
Display plot | Shows plot and blocks execution |
Complete Interactive Session Example
import matplotlib.pyplot as plt
import numpy as np
# Enable interactive mode
plt.ion()
# Create data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create interactive plot
fig, ax = plt.subplots()
line, = ax.plot(x, y, 'b-')
# Interactive modifications
line.set_color('red')
line.set_linewidth(2)
ax.set_title('Interactive Sine Wave')
ax.grid(True)
# Add another line interactively
y2 = np.cos(x)
line2, = ax.plot(x, y2, 'g--', linewidth=2)
ax.legend(['sin(x)', 'cos(x)'])
# Turn off interactive mode
plt.ioff()
plt.show() # Final display
The output shows a plot window with sine and cosine curves that were modified interactively ?
Conclusion
Interactive plotting with plt.ion() enables real-time plot updates, making it ideal for data exploration and debugging. Use plt.ioff() when you need to control exactly when updates occur, and plt.draw() to force updates in non-interactive mode.
