我想为python中的时间序列图添加趋势线,这意味着当我关注以下线程时,我的x轴(基准)的格式为datetime64[ns]
:How to add trendline in python matplotlib dot (scatter) graphs?
并运行我的代码:
import numpy as np
#Trendlines
z = np.polyfit(df1['Datum'], df1['Score'], 1)
p = np.poly1d(z)
我收到错误:
UFuncTypeError:ufunc'add'无法使用类型dtype('
我该如何解决?这个thread也没有帮助
答案 0 :(得分:0)
解决方法是:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
x = mdates.date2num(df1['Datum'])
y= df1['Score']
z = np.polyfit(x, df1['Score'], 1)
p = np.poly1d(z)
#then the plot
df1.plot('Datum', 'Score')
plt.plot(x, p(x), "r--")
通过线图和趋势线给出结果
答案 1 :(得分:0)
# date value
# 01-01-2021 141937
# 01-02-2021 41204
# 01-03-2021 2198991
# 01-04-2021 8744873
# 01-09-2021 7825446
x = df['date']
x = pd.to_datetime(x)
plt.scatter(x, y)
y = df['value'].tolist()
x = dates.date2num(list(pd.to_datetime(x)))
z = np.polyfit(x,y,1)
p = np.poly1d(z)
plt.plot(pd.to_datetime(a['date']), p(x), "r--")