python - 如何在 matplotlib 中创建作用于旋转方向的自定义 blended_transform?

标签 python matplotlib affinetransform

我正在开发一个 python GUI,它在 matplotlib Canvas 上绘制许多线条、箭头和矩形。 矩形与线对齐:线上方的旋转矩形

这是图片。

我想在矩形上设置一个变换,使垂直于直线的边的长度以轴坐标单位(transAxes)为单位,平行于直线的边以数据坐标单位(transData)为单位。

我知道 blended_transform 可用于定义 x 轴和 y 轴的不同变换。这很相似,但应用变换的方向不一定是水平和垂直方向。有没有一种方法可以定义适用于旋转方向而不是 x-y 方向的自定义混合变换?尝试创建自定义转换时,有关转换的文档不是很有帮助。

谢谢!

最佳答案

评论中的问题没有得到回答,所以需要做一些假设。假设旋转应该发生在显示空间中,轴坐标是 y 轴方向的坐标。然后一个可能的转换看起来像

trans = ax.get_xaxis_transform() + mtrans.Affine2D().rotate_deg(angle)

在这种情况下,第一个维度是数据坐标,第二个维度是轴坐标。

一些例子:

import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans

fig, ax = plt.subplots()
angle = 38 # degrees
trans = ax.get_xaxis_transform() + mtrans.Affine2D().rotate_deg(angle)

ax.plot([5,9],[0,0], marker="o", transform=trans)

rect = plt.Rectangle((5,0), width=4, height=0.2, alpha=0.3,
                     transform=trans)
ax.add_patch(rect)

ax.set(xlim=(3,10))
plt.show()

enter image description here

如果您想要围绕数据坐标中的一个点旋转,则单个变换无法完成这项工作。例如在数据空间中关于 (5,5) 的旋转,

import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans

fig, ax = plt.subplots()
ax.set(xlim=(3,10),ylim=(4,10))
fig.canvas.draw()


angle = 38 # degrees
x, y = ax.transData.transform((5,5))
_, yax = ax.transAxes.inverted().transform((0,y))
transblend = ax.get_xaxis_transform()
x, y = transblend.transform((5,yax))

trans = transblend + mtrans.Affine2D().rotate_deg_around(x,y, angle)

ax.plot([5,9],[yax,yax], marker="o", transform=trans)

rect = plt.Rectangle((5,yax), width=4, height=0.2, alpha=0.3,
                     transform=trans)
ax.add_patch(rect)


plt.show()

请注意,一旦您更改限制或图形大小,这就会失效。

关于python - 如何在 matplotlib 中创建作用于旋转方向的自定义 blended_transform?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56065114/

相关文章:

python - 如何使用 python 按行连接多个 CSV 文件?

python - Pyfst 安装错误

python - 使用虚拟 python 和 setuptool 安装 "Easy Install"

python - 使用 opencv 校正任何倾斜的矩形蒙版

python - 应如何创建 StackDriver 条目?

python - 如何为我的数据集标记或勾选 Pandas?

python - matplotlib 中的 gnuplot linecolor 变量?

python - imshow 彩色图像,错误显示为蓝色

swift - 在 Swift、Cocoa、Mac OSX 中旋转 NSImage

geometry - 3D 旋转分布的平均值和测量