3

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
PV8
  • 5,799
  • 7
  • 43
  • 87

2 Answers2

5

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

PV8
  • 5,799
  • 7
  • 43
  • 87
1
#  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--")
J. Ceron
  • 1,188
  • 10
  • 8