1

我正在使用 .csv 文件中的 10,000 个数据点,需要将常数函数拟合到两个特定范围(此处为时间),以便我可以平均它们的 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()

任何有关如何进行的建议将不胜感激!

4

1 回答 1

0

这是因为返回nnp.polyfit次多项式的系数,而不是实际拟合曲线。例如,

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 = 0a = 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))
于 2019-02-03T03:35:48.380 回答