python - 如何使用 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
解决方案
有很多不同的方法可以做到这一点。但是如果没有关于您的数据结构以及您正在寻找什么的更多信息,这是可以完成的一种方法。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
推荐阅读
- android - 如何设置随机渐变背景颜色?
- php - 如果我们有数组索引的概念,如何使用 array_column 函数从数组中获取记录?
- division - 如何有效地找到整数 k 的值,其中 q 有限地除 b ^ k?
- c# - 如何等到 C# 中的方法完成?
- asp.net - ASP.Net UserControls 不触发任何 AutoPost Back 或 Click 事件
- python - 在熊猫中选择包含关键字的列名称
- python - 调试 python tensorflow 问题
- java - Java netbeans如何在jar文件中启动gui运行
- node.js - 为什么 flash 是请求的属性而不是响应的属性?
- sql-server - 数据库查询一天一次运行缓慢