gpt4 book ai didi

python - 使用 matplotlib 围绕点旋转矩形

转载 作者:行者123 更新时间:2023-12-05 09:11:10 31 4
gpt4 key购买 nike

我想用matplotlib旋转Rectangles,但是正常的patch总是围绕Rectangle的左下角旋转。有没有办法描述更一般的转换?例如,我想围绕矩形较短边的中点旋转,以便结果看起来像时钟指针的运动。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

height = 0.1
width = 1
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_xlim([-width * 1.2, width * 1.2])
ax.set_ylim([-width * 1.2, width * 1.2])

ax.plot(0, 0, color='r', marker='o', markersize=10)
for deg in range(0, 360, 45):
rec = Rectangle((0, 0), width=width, height=height,
angle=deg, color=str(deg / 360), alpha=0.9)
ax.add_patch(rec)

Original

最佳答案

与其他答案相同,只是没有子类化和使用私有(private)属性。

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

height = 0.1
width = 1
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_xlim([-width * 1.2, width * 1.2])
ax.set_ylim([-width * 1.2, width * 1.2])
ax.plot(0, 0, color='r', marker='o', markersize=10)
point_of_rotation = np.array([0, height/2]) # A
# point_of_rotation = np.array([width/2, height/2]) # B
# point_of_rotation = np.array([width/3, height/2]) # C
# point_of_rotation = np.array([width/3, 2*height]) # D

for deg in range(0, 360, 45):
rec = plt.Rectangle(-point_of_rotation, width=width, height=height,
color=str(deg / 360), alpha=0.9,
transform=Affine2D().rotate_deg_around(*(0,0), deg)+ax.transData)
ax.add_patch(rec)
plt.show()

enter image description here

关于python - 使用 matplotlib 围绕点旋转矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60413174/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com