首页 > 解决方案 > 如何使用 matplotlib 将线性回归绘制到线段

问题描述

我有一些数据用 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

标签: pythonmatplotlibstatistics

解决方案


有很多不同的方法可以做到这一点。但是如果没有关于您的数据结构以及您正在寻找什么的更多信息,这是可以完成的一种方法。np.polyfit()此处的文档)对列表或数组中的顺序数据使用 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

推荐阅读