简体   繁体   English

在 matplotlib.pyplot 中绘制带有日期的线性回归

[英]Plotting a linear regression with dates in matplotlib.pyplot

How would I plot a linear regression with dates in pyplot?我将如何在 pyplot 中绘制带有日期的线性回归? I wasn't able to find a definitive answer to this question.我无法找到这个问题的明确答案。 This is what I've tried (courtesy of w3school's tutorial on linear regression).这是我尝试过的(由 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()

You first have to convert your dates into numbers to be able to do a regression (and to plot for that matter).您首先必须将日期转换为数字才能进行回归(并为此绘图)。 Then you can instruct matplotlib to interpret the x-values as dates to get a nicely formatted axis:然后您可以指示 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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM