Построение линейной регрессии с датами в matplotlib.pyplot - PullRequest
1 голос
/ 13 января 2020

Как бы я построил линейную регрессию с датами в 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()

1 Ответ

1 голос
/ 13 января 2020

Сначала вы должны преобразовать свои даты в числа, чтобы иметь возможность сделать регрессию (и построить график в этом отношении). Затем вы можете дать команду 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...