首页 > 解决方案 > 在 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()

标签: pythonmatplotlib

解决方案


您首先必须将日期转换为数字才能进行回归(并为此进行绘图)。然后您可以指示 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()

在此处输入图像描述


推荐阅读