无法使用rotate_deg_around()围绕特定点旋转matplotlib修补程序对象

时间:2017-03-24 13:06:16

标签: python matplotlib

我想使用rotate_deg_around()函数围绕其左下角旋转matplotlib矩形补丁对象。但是,补丁总是在某个不同的点上旋转。知道为什么rotate_deg_around()函数没有产生所需的结果吗?

我的代码如下:

f,(ax1) = plt.subplots(1,1,figsize=(6,6))
f.subplots_adjust(hspace=0,wspace=0)

ts = ax1.transData
coords = ts.transform([1,1])
tr = mpl.transforms.Affine2D().rotate_deg_around(coords[0], coords[1], 10)
t = ts + tr
rec0 = patches.Rectangle((1,1),3,2,linewidth=1,edgecolor='r',facecolor='none')
ax1.add_patch(rec0)
#Rotated rectangle patch
rect1 = patches.Rectangle((1,1),3,2,linewidth=1,edgecolor='b',facecolor='none',transform=t)
ax1.add_patch(rect1)
# Rectangles lower left corner
plt.plot([1], [1], marker='o', markersize=3, color="green")

plt.grid(True)
ax1.set_xlim(0,6)
ax1.set_ylim(-1,4)

产生如下图:

enter image description here

我跟着 Unable to rotate a matplotlib patch object about a specific point using rotate_around( )

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

简短的回答是:您需要在进行转换之前更改轴限制。否则,在将限制设置为不同的值之前,在画布上的一个点上旋转,该点位于(1,1)位置(右上角)。

更好的答案实际上如下:为了围绕数据坐标中的某个点旋转,不应该使用显示坐标来定义旋转中心,而是确切地将数据协调自身。

因此,不应先转换为显示坐标然后旋转,而应首先旋转,然后转换为显示坐标

ts = ax1.transData
coords = [1,1]
tr = matplotlib.transforms.Affine2D().rotate_deg_around(coords[0],coords[1], 10)
t = tr + ts

完整的代码(如果设置了轴限制并且哪个是图形调整大小等,则无关紧要):

import matplotlib.pyplot as plt
import matplotlib

f,(ax1) = plt.subplots(1,1,figsize=(3,3))
f.subplots_adjust(hspace=0,wspace=0)


ts = ax1.transData
coords = [1,1]
tr = matplotlib.transforms.Affine2D().rotate_deg_around(coords[0],coords[1], 10)
t = tr + ts
rec0 = matplotlib.patches.Rectangle((1,1),3,2,linewidth=1,edgecolor='r',facecolor='none')
ax1.add_patch(rec0)
#Rotated rectangle patch
rect1 = matplotlib.patches.Rectangle((1,1),3,2,linewidth=1,edgecolor='b',facecolor='none',transform=t)
ax1.add_patch(rect1)
# Rectangles lower left corner
plt.plot([1], [1], marker='o', markersize=3, color="green")

plt.grid(True)
ax1.set_xlim(0,6)
ax1.set_ylim(-1,4)

plt.show()

enter image description here