将趋势线添加到日期时间 matplotlib 折线图

Add trend line to datetime matplotlib line graph

我有一个 pandas 数据框 df:

times = pd.date_range(start="2018-09-09",end="2020-02-02")
values = np.random.rand(512)

# Make df
df = pd.DataFrame({'Time' : times, 
                   'Value': values})

我可以使用 plt.plot:

轻松绘制此图

但现在我想添加一条趋势线。我尝试使用一些答案:


哪个不起作用:

TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'float'

然后我找到了下面的问答:

但是这些效果不佳。我对这个问题的理解到此为止,我找不到其他任何东西。

到目前为止我的代码:

# Get values for the trend line analysis
x = df['Time'].dt.to_pydatetime()

# Calculate a fit line
trend = np.polyfit(x, df['Value'], 1)
fit = np.poly1d(trend)

# General plot again
figure(figsize=(12, 8))
plt.plot(x, df['Value'])
plt.xlabel('Date')
plt.ylabel('Value')

# Now trendline
plt.plot(x, fit(x), "r--")

# And show
plt.show()

一种方法是使用 matplotlib 的 date2num() function and its counterpart the num2date 函数转换日期:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as dates

np.random.seed(123)
times = pd.date_range(start="2018-09-09",end="2020-02-02")
values = np.random.rand(512)
df = pd.DataFrame({'Time' : times, 
                   'Value': values})


# Get values for the trend line analysis
x_dates = df['Time']
x_num = dates.date2num(x_dates)

# Calculate a fit line
trend = np.polyfit(x_num, df['Value'], 1)
fit = np.poly1d(trend)

# General plot again
#figure(figsize=(12, 8))
plt.plot(x_dates, df['Value'])
plt.xlabel('Date')
plt.ylabel('Value')

# Not really necessary to convert the values back into dates
#but added as a demonstration in case one wants to plot non-linear curves
x_fit = np.linspace(x_num.min(), x_num.max())
plt.plot(dates.num2date(x_fit), fit(x_fit), "r--")

# And show
plt.show()

示例输出: