python - 如何按角度旋转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()
数组的目标计算应该是这样的(请忽略红线):
如果你有什么建议,请告诉我。谢谢。
解决方案
这个问题非常有帮助,尤其是@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),这与我上面的旋转图一致。
通过这种方式,您可以旋转任何您感兴趣的点,或者编写一个循环来捕捉它们。
推荐阅读
- angular - Angular ng-content n 第一个元素
- mongodb - cloneCollection 命令中的 URI 问题
- python - 编码来自多个熊猫列的分类变量
- javascript - 在 Razor 视图中从模态谷歌地图获取位置
- java - 在终端中编译 Spring 项目时出现 NoClassDefFoundError
- apache-kafka - 使用 Kafka 代替 Spring Cloud Bus
- octobercms - 注册后如何显示flash消息
- java - 带有动态参数的 Spring bean 原型延迟初始化
- reactjs - 标注组件在底部占位符内的位置错误
- vba - 通过 Shell 命令将 Outlook.MailMessage 传递给 PowerShell 脚本