I want to add a trendline for a timeseries graph in python, that means my x-axis (Datum) has the format of datetime64[ns]
, when I am following this thread: How to add trendline in python matplotlib dot (scatter) graphs?
and run my code:
import numpy as np
#Trendlines
z = np.polyfit(df1['Datum'], df1['Score'], 1)
p = np.poly1d(z)
I get the error:
UFuncTypeError: ufunc 'add' cannot use operands with types dtype('
How can I solve this? This thread also did not help
The workaround is:
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--")
Gives the outcome with the line plot and the trendline