The purpose of my code is import serial data for logathmic regression on live data. At the current moment, all my data is filtered out instead of just the points (x,y) where y<0. I'm learning python and this is my first project, Yaa :(
import serial
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import stats
#initialize serial port
ser = serial.Serial()
ser.port = '/dev/cu.usbmodem14101' #Arduino serial port
ser.baudrate = 9600
ser.timeout = 10 #specify timeout when using readline()
ser.open()
if ser.is_open==True:
print("\nAll right, serial port now open. Configuration:\n")
print(ser, "\n") #print serial parameters
fig1 = plt.figure(figsize=(10,7))
ax1 = fig1.add_subplot(2, 1, 1)
xs = [] #store trials here (n)
ys = [] #store relative frequency here
# This function is called periodically from FuncAnimation
def animate(i, xs, ys):
#Acquire and parse data from serial port
line=ser.readline() #ascii
line_as_list = line.split(b',')
i = float(line_as_list[0])
Y = line_as_list[1]
Y_as_list = Y.split(b'\n')
Y_float = float(Y_as_list[0])
cc=str(ser.readline())
print(cc[2:][:-5])
xs.append(i)
ys.append(Y_float)
K = 0
def filter_where(xs, K):
return xs[np.where(ys > K)]
print(xs)
print(ys)
def filter_where(ys, K):
return ys[np.where(ys > K)]
print(ys)
#adding regression - commented out b/c it generates error that it is empty
#slope, intercept, r, p, std_err = stats.linregress(xs, ys)
#def myfunc(xs):
# return slope * xs + intercept
#mymodel = list(map(myfunc, xs))
plt.scatter(xs, ys)
#plt.plot(xs, mymodel)
# Draw x and y lists
ax1.clear()
ax1.plot(xs, ys)
ani = animation.FuncAnimation(fig1, animate, fargs=(xs, ys), interval=10)
plt.show()
Edit: I changed the code. I moved the filter out of the animate part. And I added the new i and y to xs and ys respectively. I made it print the serial so you can see that it is getting info.
Here is is sample output
All right, serial port now open. Configuration:
Serial<id=0x109132c50, open=True>(port='/dev/cu.usbmodem14101', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=10, xonxoff=False, rtscts=False, dsrdtr=False)
[]
[]
[]
0.30,0.011
0.70,0.011
1.11,0.013
1.51,0.005
1.91,0.006
2.31,0.012
2.71,0.004
3.12,0.005
3.52,0.004
3.92,0.014
4.32,0.005
4.72,-0.001
5.13,0.008
5.53,0.009
5.93,0.010
6.33,0.013
6.73,0.000
7.13,0.004
I couldn't get Tempman's more concise solution to work but I got this to work on the same idea. As you suggested I don't need to filter all the xs and ys in the ainmate, and I don't even need the filters to be defined in the first place. I have two variables in my serial data that work as a pair (x,y). If the y is invalid data, then the x is too. I am filtering it after parsing the serial and before appending it to rest of the data.