我有10,000个数据点从.csv文件的工作,需要不断适应功能的两个特定范围(时间在这里),这样我可以平均的Y型拦截并减去从数据的y值(电压这个案例)。
我的配合,range1fit和range2fit,显然是大小为1和我得到一个尺寸错误,当我尝试绘图,因为我想要绘制的元素之间的尺寸差的趋势线。
这里是我完整的代码:
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()
任何意见,以如何进行将不胜感激!
这是因为np.polyfit
返回多项式次数n,而不是实际的拟合曲线的系数。例如,
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]
该输出意味着,对于方程ax^3 + bx^2 + cx + d = 0
,a = 0.08703704, b = -0.81349206, c = 1.69312169, d = -0.03968254
。为了适应这种曲线的x
数据,你可以做
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')
range1fit = np.poly1d(np.polyfit(range1t,range1v,0))
range2fit = np.poly1d(np.polyfit(range2t,range2v,0))
它创建使用np.poly1d
多项式。
然后像绘制
plt.plot(range1t, rangefit1(range1t))
plt.plot(range2t, rangefit2(range2t))