python - 在 matplotlib.pyplot 中绘制带有日期的线性回归
问题描述
如何在 pyplot 中绘制带有日期的线性回归?我无法找到这个问题的明确答案。这是我尝试过的(由 w3school 的线性回归教程提供)。
import matplotlib.pyplot as plt
from scipy import stats
x = ['01/01/2019', '01/02/2019', '01/03/2019', '01/04/2019', '01/05/2019', '01/06/2019', '01/07/2019', '01/08/2019', '01/09/2019', '01/10/2019', '01/11/2019', '01/12/2019', '01/01/2020']
y = [12050, 17044, 14066, 16900, 19979, 17593, 14058, 16003, 15095, 12785, 12886, 20008]
slope, intercept, r, p, std_err = stats.linregress(x, y)
def myfunc(x):
return slope * x + intercept
mymodel = list(map(myfunc, x))
plt.scatter(x, y)
plt.plot(x, mymodel)
plt.show()
解决方案
您首先必须将日期转换为数字才能进行回归(并为此进行绘图)。然后您可以指示 matplotlib 将 x 值解释为日期以获得格式良好的轴:
import matplotlib.pyplot as plt
from scipy import stats
import datetime
x = ['01/01/2019', '01/02/2019', '01/03/2019', '01/04/2019', '01/05/2019', '01/06/2019', '01/07/2019', '01/08/2019', '01/09/2019', '01/10/2019', '01/11/2019', '01/12/2019']
y = [12050, 17044, 14066, 16900, 19979, 17593, 14058, 16003, 15095, 12785, 12886, 20008]
# convert the dates to a number, using the datetime module
x = [datetime.datetime.strptime(i, '%M/%d/%Y').toordinal() for i in x]
slope, intercept, r, p, std_err = stats.linregress(x, y)
def myfunc(x):
return slope * x + intercept
mymodel = list(map(myfunc, x))
fig, ax = plt.subplots()
ax.scatter(x, y)
ax.plot(x, mymodel)
# instruct matplotlib on how to convert the numbers back into dates for the x-axis
l = matplotlib.dates.AutoDateLocator()
f = matplotlib.dates.AutoDateFormatter(l)
ax.xaxis.set_major_locator(l)
ax.xaxis.set_major_formatter(f)
plt.show()
推荐阅读
- angular-material - 在柏树中获取第 n 个 mat-row
- github - 在将代码从 VS CODE 移动到 Github 时面临“这超出了 GitHub 的文件大小限制 100.00 MB”的错误
- javascript - 从扩展中是否可以在页面加载时以编程方式捕获站点的 CSP?
- keras - 表格数据的“卷积一维”神经网络训练中的“loss : nan”
- javascript - 在 Cognos 中应用多提示验证
- python - Pandas:WiFi 日志中按小时计算的唯一每日值
- javascript - 如何在使用 fetch api 发布响应后读取字符串值
- xml - 用 XSLT 中的元素包围匹配的兄弟姐妹
- titanium - 如何创建随机抖动的图像
- python - TypeError 'DataFrame' 对象不可调用