gpt4 book ai didi

python - 在 matplotlib.pyplot 中绘制日期的线性回归

转载 作者:行者123 更新时间:2023-12-01 06:34:53 25 4
gpt4 key购买 nike

如何在 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()

enter image description here

关于python - 在 matplotlib.pyplot 中绘制日期的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59723501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com