0

I got a time series pandas dataFrame, which I can plot it like this: enter image description here

By adding a trend line, I want make it like this: enter image description here

The original data is like:

2021-04-21     4.361371
2021-04-22     2.907580
2021-04-23    17.385541
2021-04-26    11.590361
2021-04-27     7.726907
2021-04-28    24.718008
2021-04-29    49.812005
2021-04-30    66.541337
2021-05-04    77.694225
2021-05-05    85.129483
2021-05-06    90.086322
2021-05-07    90.863076
2021-05-10    90.437197
2021-05-11    93.422573

Follow this: How can I draw scatter trend line on matplot? Python-Pandas

I can simply make regression with bellow code:

y = xdf.values
x = np.arange(len(y))
z = np.polyfit(x,y,1)
p = np.poly1d(z)

with this code plot it seperately:

import matplotlib.pyplot as plt
plt.plot(x, p(x))

I get:

enter image description here

Now, I only need my last step, how do I integrate this into my original plot? Note, I only need place part of the 'trend' into the original, no need from start to the end.

yunfei
  • 526
  • 2
  • 6
  • 20

2 Answers2

1

Since the x-axis is a time series, we can add a trend line with the same number of x-axis. I am not sure if this is the best way to do it.

import pandas as pd
import numpy as np
import io
import matplotlib.pyplot as plt

data = '''
date value
2021-04-21     4.361371
2021-04-22     2.907580
2021-04-23    17.385541
2021-04-26    11.590361
2021-04-27     7.726907
2021-04-28    24.718008
2021-04-29    49.812005
2021-04-30    66.541337
2021-05-04    77.694225
2021-05-05    85.129483
2021-05-06    90.086322
2021-05-07    90.863076
2021-05-10    90.437197
2021-05-11    93.422573
'''
df = pd.read_csv(io.StringIO(data), delim_whitespace=True)


fig, ax = plt.subplots()
x = df['date']
y = df['value']
ax.plot(x, y)

xx = np.arange(len(df))
z = np.polyfit(xx, y, 1)
p = np.poly1d(z)
ax.plot(xx,p(xx),"r--")

plt.setp(ax.get_xticklabels(), rotation=45, ha='right')

plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
0

I get it integrated, but not very fancy, it is impacted by weekends:

enter image description here

here is my code:

y = xdf.values
x = np.arange(len(y))
z = np.polyfit(x,y,1)
p = np.poly1d(z)

x1 = x[4:10]
y1 = p(x1)
x2 = xdf.index[4:10]
fig = xdf.plot(label='data')
fig.plot(x2, y1, label='trend')
yunfei
  • 526
  • 2
  • 6
  • 20