Skip to content
Advertisement

Add trend line to datetime matplotlib line graph

I have a pandas dataframe df:

JavaScript

And I can plot this easily using plt.plot:

plot1

But now I want to add a trendline. I tried using some answers:

How can I draw scatter trend line on matplot? Python-Pandas
Which doesn’t work:

JavaScript

Then I found the following question and answer:

TypeError: ufunc subtract cannot use operands with types dtype(‘<M8[ns]’) and 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:

JavaScript

Advertisement

Answer

One approach is to convert the dates using matplotlib’s date2num() function and its counterpart the num2date function:

JavaScript

Sample output: enter image description here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement