Designing a plotting function
The user wants a Python function to plot real-time data using matplotlib animation. I think I'll focus on using FuncAnimation and create a generic function that can work with either sensor data or random data.
I'll define libraries like matplotlib and deque to help, and I'll design a function, live_plotter, that takes a data-fetching function and integrates it into an animation format. The goal is to create a simple stand-alone script for the user.Creating a real-time plotting function
I'm thinking about how to create a function called realtime_plot, which takes a data generator and plots real-time data using matplotlib's FuncAnimation. The function will yield either coordinates (t, y) or just y, while the x value auto-increments.
Inside the function, I'll set up the figure, axis, and line elements. I'll keep it simple by focusing on y values and using a random data generator as an example, highlighting the workflow for the user.Developing the update function
I'm putting together the realtime_plot function to handle both callable data sources and iterables by using next(). The function will have parameters for the interval and max points shown on the plot.
Inside, I’ll set up the figure and axis, then define an update function that retrieves data from the source. If the data is a tuple, I'll assign x and y values; otherwise, I'll use the frame count for x. To avoid rebinding issues, I'll use deques to manage xs and ys, keeping them at the specified maximum length easily.Finalizing real-time plotting
I'm working on the initialization for the realtime_plot function, setting x and y limits and preparing the line for plotting. I’m using FuncAnimation, ensuring it returns the right artists for the blit feature to work smoothly.
It's important to handle cases where xs might be empty by keeping the limits constant until there are enough points. I plan to show examples of how to use the function with both a random data generator and a sine wave generator to give the user clear options. I'll include necessary imports as well!Completing the real-time plot function
I'm finalizing the realtime_plot function that uses FuncAnimation from matplotlib. This function will take a data source that can be either callable or an iterator, returning data points for real-time plotting.
I’ll include checks for x and y limits to ensure they update based on the data. Also, I'll note that using blit with FuncAnimation handles updates automatically, so no need to call plt.pause(). I’ll provide clear comments and guidelines for users running the script, especially in environments like Jupyter. Now, let's pull everything together! Here’s a self‑contained example using matplotlib.animation.FuncAnimation and a reusable helper function you can plug any real‑time data source into.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from collections import deque
import random
import time
def realtime_plot(data_source, interval=100, max_points=200):
"""
Plot real-time data using matplotlib.animation.FuncAnimation.
Parameters
----------
data_source : callable or iterator
- If callable: called once per frame, should return either
y # x will be frame index
or (x, y)
- If iterator/generator: next(data_source) should return the same.
interval : int
Delay between frames in milliseconds.
max_points : int
Maximum number of points to keep on the screen.
"""
fig, ax = plt.subplots()
xs = deque(maxlen=max_points)
ys = deque(maxlen=max_points)
(line,) = ax.plot([], [], lw=2)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Real-time data")
def get_next_value():
if callable(data_source):
return data_source()
else:
return next(data_source)
def init():
line.set_data([], [])
return line,
def update(frame_idx):
value = get_next_value()
# Support both y and (x, y)
if isinstance(value, (tuple, list)) and len(value) == 2:
x, y = value
else:
x = frame_idx
y = value
xs.append(x)
ys.append(y)
line.set_data(xs, ys)
# Update x-limits to follow data
if len(xs) > 1:
ax.set_xlim(min(xs), max(xs))
else:
ax.set_xlim(0, max_points)
# Update y-limits with a small margin
if len(ys) > 0:
ymin, ymax = min(ys), max(ys)
if ymin == ymax:
# Avoid zero-height range
ymin -= 0.5
ymax += 0.5
margin = 0.05 * (ymax - ymin)
ax.set_ylim(ymin - margin, ymax + margin)
return line,
ani = FuncAnimation(
fig,
update,
init_func=init,
interval=interval,
blit=True,
)
plt.show()
return ani
Example usages
- Random data, x = frame index
def random_data():
# Simulate reading from a sensor
return random.random()
realtime_plot(random_data, interval=100, max_points=100)
- Generator that provides (time, value)
import math
import time
def sine_wave():
t0 = time.time()
while True:
t = time.time() - t0
y = math.sin(2 * math.pi * 0.5 * t) # 0.5 Hz sine
yield t, y
gen = sine_wave()
realtime_plot(gen, interval=50, max_points=300)
You can replace random_data() or sine_wave() with any function/generator that reads from your real-time source (serial port, socket, sensor API, etc.).