首页 > 解决方案 > 如何按角度旋转python / numpy中的一维线图数组?

问题描述

我想水平旋转折线图。到目前为止,我有目标角度,但我无法旋转图形阵列(印迹中的蓝色图形)。

import matplotlib.pyplot as plt
import numpy as np

x = [5, 6.5, 7, 8, 6, 5, 3, 4, 3, 0]
y = range(len(x))
best_fit_line = np.poly1d(np.polyfit(y, x, 1))(y)

angle = np.rad2deg(np.arctan2(y[-1] - y[0], best_fit_line[-1] - best_fit_line[0]))
print("angle: " + str(angle))

plt.figure(figsize=(8, 6))
plt.plot(x)
plt.plot(best_fit_line, "--", color="r")
plt.show()

在此处输入图像描述

数组的目标计算应该是这样的(请忽略红线):

在此处输入图像描述

如果你有什么建议,请告诉我。谢谢。

标签: pythonnumpy

解决方案


这个问题非常有帮助,尤其是@Mr Tsjolder 的回答。根据您的问题,我必须从您计算的角度中减去 90 以获得您想要的结果:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import transforms

x = [5, 6.5, 7, 8, 6, 5, 3, 4, 3, 0]
y = range(len(x))
best_fit_line = np.poly1d(np.polyfit(y, x, 1))(y)

angle = np.rad2deg(np.arctan2(y[-1] - y[0], best_fit_line[-1] - best_fit_line[0]))
print("angle: " + str(angle))

plt.figure(figsize=(8, 6))

base = plt.gca().transData
rotation = transforms.Affine2D().rotate_deg(angle - 90)

plt.plot(x, transform = rotation + base)
plt.plot(best_fit_line, "--", color="r", transform = rotation + base)

旋转图


追问:如果我们只需要旋转点的数值怎么办?

那么 matplotlib 方法仍然很有用。从rotation我们上面介绍的对象中,matplotlib 可以提取出变换矩阵,我们可以用它来变换任意点:

# extract transformation matrix from the rotation object
M = transforms.Affine2DBase.get_matrix(rotation)[:2, :2]

# example: transform the first point
print((M * [0, 5])[:, 1])

[-2.60096617 4.27024297]

切片是为了得到我们感兴趣的尺寸,因为旋转只发生在 2D 中。您可以看到原始数据中的第一个点被转换为 (-2.6, 4.3),这与我上面的旋转图一致。

通过这种方式,您可以旋转任何您感兴趣的点,或者编写一个循环来捕捉它们。


推荐阅读