简体   繁体   English

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

[英]Add trend line to datetime matplotlib line graph

I have a pandas dataframe df:我有一个 pandas dataframe 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})

And I can plot this easily using plt.plot:我可以使用 plt.plot 轻松实现 plot:

情节1

But now I want to add a trendline.但现在我想添加一条趋势线。 I tried using some answers:我尝试使用一些答案:

How can I draw scatter trend line on matplot? 如何在 matplot 上绘制散点趋势线? Python-Pandas Python-熊猫
Which doesn't work:哪个不起作用:

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

Then I found the following question and answer:然后我找到了以下问题和答案:

TypeError: ufunc subtract cannot use operands with types dtype('<M8[ns]') and dtype('float64') 类型错误:ufunc 减法不能使用类型为 dtype('<M8[ns]') 和 dtype('float64') 的操作数

But these don't work as well.但这些也不起作用。 There my understanding of the issue stops, and I can't find anything else.我对这个问题的理解停止了,我找不到其他任何东西。

My code so far:到目前为止我的代码:

# 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()

One approach is to convert the dates using matplotlib's date2num() function and its counterpart the num2date function:一种方法是使用 matplotlib 的date2num() function 及其对应的num2date function 转换日期:

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()

Sample output:样品 output: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM