【问题标题】:Fitting timestamp TZ-aware does not show the year x-label拟合时间戳 TZ-aware 不显示年份 x-label
【发布时间】:2020-04-10 01:18:03
【问题描述】:

我想线性拟合一个 8 年的时间序列数据,在 x 轴标签中显示年份。
出现问题是因为我的dataframe 中有TZ-aware 日期时间列。所以,我不能直接将我的拟合代码与这种类型的时间戳一起使用。该文件是here。这就是我所做的。

# Convert TZ-aware timestamp intu numbers
ts = df['Timestamp'].apply(lambda x:x.toordinal()).sort_values()

# Fit
from numpy.polynomial.polynomial import polyfit
y = df.data
x = ts

fig, (ax) = plt.subplots(1,1, figsize=(10, 6))
ax.scatter(x, y)

b, m = polyfit(x, y, 1)
plt.plot(x, b + m * x, 'blue', linewidth=1.5)

plt.show()

结果如下。

正如预期的那样,它有效。但是,x 轴显示的是数字而不是年份。我想在 x 轴上显示 month-year 标签。

任何帮助都会很棒,并在此先感谢。

【问题讨论】:

    标签: python timezone time-series regression


    【解决方案1】:

    @Dodge 在这个post 的代码给了我解决方案。

    from pandas.plotting import register_matplotlib_converters
    register_matplotlib_converters()
    
    y_values = df.loc[:, "data"]
    x_values = np.linspace(0,1,len(df.loc[:, "data"]))
    poly_degree = 1
    
    coeffs = np.polyfit(x_values, y_values, poly_degree)
    poly_eqn = np.poly1d(coeffs)
    y_hat = poly_eqn(x_values)
    
    plt.figure(figsize=(8,4))
    plt.plot(df.loc[:, "Timestamp"], df.loc[:,"data"], "ro")
    plt.plot(df.loc[:, "Timestamp"],y_hat)
    plt.ylabel('data')
    plt.xlabel('Year')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2021-08-31
      • 1970-01-01
      • 2018-03-19
      相关资源
      最近更新 更多