Python 度角和矢量化

Degree Angle and Vecorization with Python

每次我 运行 新数据集上的脚本时,角度线都会移动。每次读入新数据集时,我希望两条线分别成 345 度(绿线)和 330 度(红线)度角。

我的代码有什么问题?

结果应如下所示:

第一个数据集

data = np.array([10.79,10.87,10.94,10.95,11,11.5,10.89,11.45,11.94,12.17,12.45,12.09,13.65,13.5,13.25,13.18,13.28,
             13.45,13.81,13.8,14.08,14.09,14.48,14.5,14.08,14.54,14.6,15.48,16,17.049999,17.219999,16.99,
             17.23,17.200001,17.110001,18.190001,23.540001,22.25,21.15,22.09,22.85,21.4,21.41,20.780001,18.84,
             18.389999,18.09,18.280001,17.959999,21.969999,21.120001,20.25,19.879999,21.309999,21.84])

第二个数据集

data = np.array([12.44,12.02,12.58,12.09,12,11.98,12.19,11.75,11.44,11.4,10.68,10.46,10.95,10.6,11.44,
             10.6,10.41,10.3,11.45,12.5,12.65,11.62,11.45,11.16,10.8,12.5,12.23,13.99,12.49,13.49,12.69,12.72,
             12.81,13.1,12.89,13.50,13.35])

脚本

import matplotlib.pyplot as plt
import numpy as np
import math
from scipy import signal

for number in data:

signal_max = (data > np.roll(data,1)) & (data > np.roll(data,-1))
signal_min = (data < np.roll(data,1)) & (data < np.roll(data,-1))


xm = np.argmax(data)
ym = np.amax(data)

angle1 = 345 # green
angle2 = 330 # red

x1, y1 = xm + len(data)-xm, ym + math.tan(angle1 * math.pi/180) * len(data)-xm
x2, y2 = xm + len(data)-xm, ym + math.tan(angle2 * math.pi/180) * len(data)-xm

plt.plot( [ xm, x1 ], [ym, y1 ], '-', color='g')
plt.plot( [ xm, x2 ], [ym, y2 ], '-', color='r')
plt.plot(data)
plt.show()

在图上可视化角度时应该注意的一件事是图的纵横比。如果绘图的纵横比不相等,那么可视化的角度将不会像您期望的那样!

您可以将角度的绘图整理为:

angle1 = np.deg2rad(345) # green
angle2 = np.deg2rad(330) # red

x1, y1 = np.cos(angle1), np.sin(angle1)
x2, y2 = np.cos(angle2), np.sin(angle2)

plt.plot( [ xm, xm + x1 ], [ym, ym + y1 ], '-', color='g')
plt.plot( [ xm, xm + x2 ], [ym, ym + y2 ], '-', color='r')

为确保纵横比相等,您可以使用 plt.gca().set_aspect('equal')

如果你想改变线条的长度,你可以引入一个比例变量:

scale = 2
x1, y1 = scale * np.cos(angle1), scale * np.sin(angle1)
x2, y2 = scale * np.cos(angle2), scale * np.sin(angle2)

因此,如果您希望线条到达数据的末尾,您可以设置

scale = data.size - xm