Certainly! Below is a Python example that reads x, y data points from a serial port and plots them as an animated vector plot using matplotlib. The program assumes the data is sent as lines of text in the format:
code
x_value,y_value
Requirements
pyserial for serial communication (pip install pyserial)
matplotlib for plotting (pip install matplotlib)
Example Code
python
import serial
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from collections import deque
# Configure your serial port and baud rate here
SERIAL_PORT = 'COM3' # or '/dev/ttyUSB0' on Linux/Mac
BAUD_RATE = 9600
# Number of points to keep in the plot
MAX_POINTS = 100
def read_serial_data(ser):
"""Generator to read lines from serial and parse x,y floats."""
while True:
try:
line = ser.readline().decode('utf-8').strip()
if not line:
continue
x_str, y_str = line.split(',')
x, y = float(x_str), float(y_str)
yield x, y
except (ValueError, serial.SerialException):
# Ignore malformed lines or serial errors
continue
def main():
# Open serial port
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
# Deques to store points
x_data = deque(maxlen=MAX_POINTS)
y_data = deque(maxlen=MAX_POINTS)
# Initialize plot
fig, ax = plt.subplots()
ax.set_xlim(-10, 10) # Adjust limits as needed
ax.set_ylim(-10, 10)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Real-time Vector Plot from Serial Data')
# Initialize a line object for the vector plot
# We'll plot vectors from origin (0,0) to (x,y)
vector_line, = ax.plot([], [], 'r-', lw=2)
point_scatter = ax.scatter([], [], c='blue')
# Serial data generator
data_gen = read_serial_data(ser)
def update(frame):
try:
x, y = next(data_gen)
x_data.append(x)
y_data.append(y)
# Update vector line from origin to latest point
vector_line.set_data([0, x], [0, y])
# Update scatter plot with all points
point_scatter.set_offsets(list(zip(x_data, y_data)))
# Optionally adjust axis limits dynamically
all_x = list(x_data) + [0]
all_y = list(y_data) + [0]
ax.set_xlim(min(all_x) - 1, max(all_x) + 1)
ax.set_ylim(min(all_y) - 1, max(all_y) + 1)
except StopIteration:
pass
return vector_line, point_scatter
ani = animation.FuncAnimation(fig, update, interval=50, blit=True)
plt.show()
ser.close()
if __name__ == '__main__':
main()
How it works:
The program opens the serial port and reads lines continuously.
Each line is expected to be x,y.
It keeps the last MAX_POINTS points in memory.
It plots a red vector line from the origin (0,0) to the latest (x,y) point.
It also plots all received points as blue dots.
The plot updates every 50 ms.
Notes:
Change SERIAL_PORT and BAUD_RATE to match your device.
Adjust axis limits or remove dynamic scaling if you want fixed axes.
Make sure your device sends data in the correct format and baud rate.
You can extend this to handle more complex data or multiple vectors.
If you want me to help with a specific device or data format, just ask!