Home > Back-end >  Extraplotating a trendline Python
Extraplotating a trendline Python

Time:10-15

Hello I have this python code which calculates a trendline based on two pivots and then extrapolates it into the future. I wonder how do I get a vector of extrapolated trendline values (in a list) - say from 1000 to 1050? I need this vector to operate on it. So far I can only plot these values.

import numpy as np
import matplotlib.pyplot as plt

y = np.array([13.6700,14.4900])

x = np.array([992,1000])
x2=np.array([1001,1010])

p = np.polyfit(x, y, 1)
f = np.poly1d(p)

plt.plot(x, y, 'bo', label="Data")
plt.plot(x,f(x), 'r:',label="Polyfit")
plt.plot(x2,f(x2), 'b-',label="Polyfit")
print(p)
print(f(x2))

f(1010)

CodePudding user response:

You can use numpy.arange to create an array of Xs and apply f:

import numpy as np
xs = np.arange(1000, 1051)
ys = f(xs)

output:

>>> xs
array([1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010,
       1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021,
       1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032,
       1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043,
       1044, 1045, 1046, 1047, 1048, 1049, 1050])

>>> ys
array([14.49  , 14.5925, 14.695 , 14.7975, 14.9   , 15.0025, 15.105 ,
       15.2075, 15.31  , 15.4125, 15.515 , 15.6175, 15.72  , 15.8225,
       15.925 , 16.0275, 16.13  , 16.2325, 16.335 , 16.4375, 16.54  ,
       16.6425, 16.745 , 16.8475, 16.95  , 17.0525, 17.155 , 17.2575,
       17.36  , 17.4625, 17.565 , 17.6675, 17.77  , 17.8725, 17.975 ,
       18.0775, 18.18  , 18.2825, 18.385 , 18.4875, 18.59  , 18.6925,
       18.795 , 18.8975, 19.    , 19.1025, 19.205 , 19.3075, 19.41  ,
       19.5125, 19.615])

Alternatively, if you want the bounds and a fixed number of points, use numpy.linspace:

xs = np.linspace(1000, 1050, 200) # 200 points between 1000 and 1050
ys = f(xs)
  • Related