1

I am working with 10,000 data points from a .csv file and need to fit constant functions to two specific ranges (of time here) so that I can average their y-intercepts and subtract that from the y-values of the data (voltage in this case).

My fits, range1fit and range2fit, are apparently of size 1 and I am getting a size error when I try to plot the trendlines because of a size difference between the elements I am trying to plot.

Here is my full code:

import numpy as np
import pandas
import matplotlib.pyplot as plt
import scipy.stats as sps


# r1: run 1, r2: run 2, etc
r1 = pandas.read_csv("9Vrun1.csv") 
r2 = pandas.read_csv("9Vrun2.csv")
r3 = pandas.read_csv("9Vrun3.csv")
r4 = pandas.read_csv("9Vrun4.csv")
r5 = pandas.read_csv("9Vrun5.csv")
r = (r1 + r2 + r3 + r4 +r5)/5


time = r["TIME"]
voltage = r["CH1"]
n = 10E3 # number of recordings per sec


# ranges on flat areas either side of the peak
range1t = time[time.between(-0.0572061,0.016112)]
range1v = voltage[time.between(-0.0572061,0.016112)]
range2t = time[time.between(0.0737799,0.142302)]
range2v = voltage[time.between(0.0737799,0.142302)]


# fit ranges with constant lines
range1fit = np.polyfit(range1t,range1v,0)
range2fit = np.polyfit(range2t,range2v,0)


plt.plot(time, voltage)
plt.plot(range1t, range1fit)
plt.plot(range2t, range2fit)
plt.title('Voltage vs. Time with Target (power supply range: [-9.0, 9.0 V])' )
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

Any advice as to how to proceed would be greatly appreciated!

1 Answers1

0

It's because np.polyfit returns the coefficients of the polynomial for degree n, not the actual fitted curve. For example,

x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
z = np.polyfit(x, y, 0) # Fit with polynomial of degree 0
z3 = np.polyfit(x, y, 3) # Fit with polynomial of degree 3
print(z)
print(z3)

[-0.]
[ 0.08703704 -0.81349206  1.69312169 -0.03968254]

This output means that for the equation ax^3 + bx^2 + cx + d = 0, a = 0.08703704, b = -0.81349206, c = 1.69312169, d = -0.03968254. To fit this curve to the x data, you can do

w = np.poly1d(z) # Create polynomial using the coefficients in z in the forma above
w3 = np.poly1d(z3)

# Plot raw data
plt.plot(x, y, 'b')
# Plot constant line
plt.plot(x, w(x), 'g')
#Plot fitted curve
plt.plot(x, w3(x), 'r')

The plot is here. For your code, since you're plotting a line with slope zero, you can do

range1fit = np.poly1d(np.polyfit(range1t,range1v,0))
range2fit = np.poly1d(np.polyfit(range2t,range2v,0))

which creates the polynomial using np.poly1d.

Then plot like

plt.plot(range1t, rangefit1(range1t))
plt.plot(range2t, rangefit2(range2t))
m13op22
  • 2,168
  • 2
  • 16
  • 35