如何从时间序列数据集中绘制我的OLS线图?

问题描述 投票:0回答:1

我正在尝试绘制一条直线OLS线的图形,而我得到的是多条OLS线,如您在所附图像中看到的。我的数据集有2个时间间隔。我该怎么做?

  import numpy as np
    import statsmodels.api as sm
    import pandas as pd
    from matplotlib import pyplot as plt
    #import data
    df = pd.read_csv('Yearly_Mean_Data_1973-2019.csv', delimiter=',', index_col=['Date'], usecols=['Date', 'T'],
                     parse_dates=True).dropna()
    #Assign x,y
    X = [i for i in range(0, len(df))]
    X = np.reshape(X, (len(X), 1))
    Y = df.values
    X = sm.add_constant(X)
    #model creation
    model = sm.OLS(Y, X)
    results = model.fit()
    trend = results.predict(X)
    slope = results.params[1]
    intercept = results.params[0]

    print(results.summary())
    plt.plot(X, Y, '--')
    plt.plot(X, trend)
    plt.title('Linear Regression for Temperature 1973-2019')
    plt.xlabel('Date')
    plt.ylabel('Temperature($^\circ$C)')

enter image description here

python graph time-series linear-regression timeserieschart
1个回答
0
投票

为了澄清,您正在尝试将1个图拆分为2个不同的图,对吗?

您可以使用pyplot.subplot添加另一个图。https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.subplot.html

使用示例:https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/subplot.html

© www.soinside.com 2019 - 2024. All rights reserved.