python - 绘制趋势线 Python
问题描述
您好,我有这个 python 代码,它根据两个枢轴计算趋势线,然后将其外推到未来。我想知道如何获得外推趋势线值的向量(在列表中)——比如从 1000 到 1050?我需要这个向量来操作它。到目前为止,我只能绘制这些值。
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)
解决方案
您可以使用numpy.arange
创建一个 Xs 数组并应用f
:
import numpy as np
xs = np.arange(1000, 1051)
ys = f(xs)
输出:
>>> 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])
或者,如果您想要边界和固定数量的点,请使用numpy.linspace
:
xs = np.linspace(1000, 1050, 200) # 200 points between 1000 and 1050
ys = f(xs)
推荐阅读
- regex - 删除两个字符串之间的所有字符串
- reactjs - React/Redux:动作已分派,状态未更新
- sql - 我们如何分块执行 SQL Merge 查询?
- session - 实现 Kubernetes 部署具有短寿命和独占用户会话的有状态应用程序?
- java - Tomcat 8.5.33 Java WebApp 突然变慢了
- android - 没有找到类“androidx.core.widget.DrawerLayout”
- excel - 使用宏 excel 将工作表标题自动格式化为所有其他工作表
- r - 语法 - R 数据帧
- c - 在 C 中生成有效的数独谜题
- gradle - 更改 KAPT 类生成路径