【发布时间】:2021-11-25 22:24:54
【问题描述】:
我正在尝试列出 4 个不同数据集的最小值和最大值。这些数据集是我在实验室中进行的几次测试的四阶多项式拟合。我在下面制作了一个示例代码来说明有什么困难。数据集的数组具有不同的长度并从不同的 x 值开始。这就是为什么我没有设法用一个简单的 for 循环来解决这个问题的原因。
蓝色和红色的线条显示了最小和最大数组在绘制时的样子。
我希望通过示例代码一切都清楚。
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 4 10:49:21 2021
@author: Lodewijk
"""
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from numpy import arange
#%% Creating X and Y example values
XTest1=list(range(0,40))
YTest1=np.empty(len(XTest1))
XTest2=list(range(10,40))
YTest2=np.empty(len(XTest2))
XTest3=list(range(2,40))
YTest3=np.empty(len(XTest3))
XTest4=list(range(5,38))
YTest4=np.empty(len(XTest4))
for i in range(len(XTest1)):
YTest1[i]=math.sin(XTest1[i])
for i in range(len(XTest2)):
YTest2[i]=3*math.sin(XTest2[i])
for i in range(len(XTest3)):
YTest3[i]=2*math.sin(XTest3[i])-0.5
for i in range(len(XTest4)):
YTest4[i]=0.5*math.sin(XTest4[i])+1
plt.plot(XTest1,YTest1, label='Data 1')
plt.plot(XTest2,YTest2, label='Data 2')
plt.plot(XTest3,YTest3, label='Data 3')
plt.plot(XTest4,YTest4, label='Data 4')
plt.legend()
plt.show()
#%% Making a 4th order polynomial best fit graph through the data sets
def objective_4(x,a,b,c,d,e):
return a * x**4 +b*x**3 +c*x**2+d*x+e
pars, cov = curve_fit(objective_4, XTest1,YTest1)
x_line1 = arange(min(XTest1), max(XTest1), 1)
a, b, c, d, e = pars
y_line1 = objective_4(x_line1, a, b, c, d, e)
pars, cov = curve_fit(objective_4, XTest2,YTest2)
x_line2 = arange(min(XTest2), max(XTest2), 1)
a, b, c, d, e = pars
y_line2 = objective_4(x_line2, a, b, c, d, e)
pars, cov = curve_fit(objective_4, XTest3,YTest3)
x_line3 = arange(min(XTest3), max(XTest3), 1)
a, b, c, d, e = pars
y_line3 = objective_4(x_line3, a, b, c, d, e)
pars, cov = curve_fit(objective_4, XTest4,YTest4)
x_line4 = arange(min(XTest4), max(XTest4), 1)
a, b, c, d, e = pars
y_line4 = objective_4(x_line4, a, b, c, d, e)
plt.plot(x_line1,y_line1, label='Test1')
plt.plot(x_line2,y_line2, label='Test2')
plt.plot(x_line3,y_line3, label='Test3')
plt.plot(x_line4,y_line4, label='Test4')
plt.legend()
plt.show()
【问题讨论】:
标签: python matplotlib max min