Issue
I got a time series pandas dataFrame, which I can plot it like this:
By adding a trend line, I want make it like this:
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:
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.
Solution
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()
Answered By - r-beginners
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.