我有一些数据用 matplotlib 绘制为线,长度为 250 点。我可以拟合整个数据集。但是,我希望使用最小二乘法拟合并绘制最后 50 个数据点的回归线。最好的方法是什么? (下面是我的情节代码。)
j = 0
for line, rank in sortedSymbols:
series = getattr(self, line)["CLOSE"]
dates = pd.to_datetime(getattr(self, line)["DATE"]).dt.date
ax.plot(dates.iloc[-250:], series.iloc[-250:]/series.iloc[-250] * (40+j), label = line)
j += 10
最佳答案
有很多不同的方法可以做到这一点。但是,如果没有有关您的数据结构以及您到底在寻找什么的更多信息,这是可以完成的一种方法。 np.polyfit()
(文档 here )对列表或数组中的顺序数据使用 OLS 回归。
import numpy as np
j = 0
for line, rank in sortedSymbols:
series = getattr(self, line)["CLOSE"]
dates = pd.to_datetime(getattr(self, line)["DATE"]).dt.date
#Calculate the slope and intercept of fitted curve based on last 50 datapoint using the values
#you plotted before with 1 specified for a linear best fit line
slope, intercept = np.polyfit(dates.iloc[-50:].index,series.iloc[-50:]/series.iloc[-250] * (40+j),1)
#plot the trend line
ax.plot(dates.iloc[-50:],slope*dates.iloc[-50:].index+intercept,label=line)
j += 10
关于python - 如何使用 matplotlib 绘制线段的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57014336/