import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from collections import deque
def plot_realtime_data(max_points=200, update_interval=50, noise_level=0.05):
"""
Plots real-time streaming data using matplotlib animation.
This example simulates a noisy sine wave that scrolls in real-time.
New data points are added on the right, and old points are removed
from the left to maintain a fixed window size.
Parameters:
- max_points (int): Maximum number of points to display (window size).
- update_interval (int): Delay between updates in milliseconds.
- noise_level (float): Standard deviation of Gaussian noise added to data.
Usage:
plot_realtime_data()
"""
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_title('Real-Time Data Plot')
ax.set_xlabel('Time (samples)')
ax.set_ylabel('Value')
ax.grid(True, alpha=0.3)
# Use deque for efficient append/pop from left
xdata = deque(maxlen=max_points)
ydata = deque(maxlen=max_points)
# Initial empty line
line, = ax.plot([], [], 'b-', linewidth=2, animated=True)
def init():
"""Initialize the plot."""
ax.set_xlim(0, max_points)
ax.set_ylim(-2, 2)
return line,
def update(frame):
"""Update function called on each animation frame."""
# Generate new data point: noisy sine wave
t = frame * 0.1 # Time scaling
new_y = np.sin(t) + noise_level * np.random.randn()
# Append new data (deque handles maxlen automatically)
xdata.append(len(xdata))
ydata.append(new_y)
# Update line data
line.set_data(xdata, ydata)
# Adjust y-limits dynamically
if len(ydata) > 0:
y_min, y_max = min(ydata), max(ydata)
margin = 0.1 * (y_max - y_min) if y_max > y_min else 0.2
ax.set_ylim(y_min - margin, y_max + margin)
return line,
# Create animation: runs indefinitely with given interval
ani = FuncAnimation(
fig, update, init_func=init,
frames=None, interval=update_interval, blit=True, cache_frame_data=False
)
plt.tight_layout()
plt.show(block=True)
return ani # Return animation object for potential saving/control
# Example usage:
# ani = plot_realtime_data(max_points=100, update_interval=100, noise_level=0.1)
How it works:
- Data Generation: A noisy sine wave (
np.sin(t) + noise) simulates real-time sensor/streaming data.
- Scrolling Window:
deque(maxlen=max_points) automatically removes old points as new ones arrive.
- Animation:
FuncAnimation calls update() every update_interval ms, redrawing only changed parts (blit=True for speed).
- Customization: Adjust parameters or modify
update() to use real data (e.g., from a queue, sensor, or file).
- Stopping: Close the plot window to stop. For scripts, use
ani.event_source.stop().
This runs smoothly in most environments (e.g., scripts, Jupyter with %matplotlib tk or notebook). For saving: ani.save('realtime.gif', writer='pillow').