Python Forum
Matplotlib - automatic update - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Matplotlib - automatic update (/thread-36775.html)



Matplotlib - automatic update - frohr - Mar-29-2022

Hi all,
I am reading data from serial and then plot them. Everytime I wan to read from serial I send a char and get required data.
I want to change my code to update both plots automatically.
1) Send char to serial
2) Read 30k samples to array
3) Plot data (time signal and FFT)
4) Send char to serial
5) Read 30k samples to array
6) Update plots with new data without close plot windows

I am thinking about and the best solution for me is to have one window with one plot and 2 buttons to change the auto-update plot.

Could you help me with this please? Thanks!

This is my code:

import serial
import struct
import matplotlib.pyplot as plt
import scipy.fft
import numpy as np
from scipy.fftpack import fft

ser = serial.Serial(port='COM8', baudrate=2000000)
SAMPLES=30000
SPS = 15000
s = struct.Struct('<' + str(SAMPLES) + 'f')
T = 1.0 / SPS
unpacked_data1 = []

def serial_read():
    ser.reset_input_buffer()
    ser.write("r".encode())
    serial_data = ser.read(SAMPLES*4)
    unpacked_data = s.unpack(serial_data)
    unpacked_data1[0:SAMPLES] = unpacked_data[0:SAMPLES]
    ser.close

serial_read()
plt.plot(unpacked_data1[0:SAMPLES])

x = np.linspace(0.0, SAMPLES*T, SAMPLES)
y = unpacked_data1
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), SAMPLES//2)
fig, ax = plt.subplots()
ax.plot(xf, 2.0/SAMPLES * np.abs(yf[:SAMPLES//2]))

plt.show()  



RE: Matplotlib - automatic update - deanhystad - Mar-29-2022

Does your existing code work for making 1 plot?