如何使用矩形补丁在python中创建圆形几何

时间:2020-03-08 13:03:56

标签: python matplotlib

我想使用矩形补丁在python中创建圆形几何图形,所以我想创建一个矩形补丁,当我查看文档时可以通过

创建
rectangle = plt.Rectangle((x,y), width, height)
plt.gca().add_patch(rectangle)

,然后我想以圆形方式放置它,以使其创建看起来像探测器的形状,并以矩形作为“探测器块”。我该如何实现?谢谢

最终结果应如图所示 Final Result

1 个答案:

答案 0 :(得分:0)

要创建具有N个矩形的图形,请将一个圆形均匀地分成N个部分,从而将角度分为2pi/N。 x和y是后续角度的正弦和余弦乘以内圆的半径。

矩形本身需要按段的平均角度旋转。而且-90度可以使宽度垂直于半径。

请注意,正弦和余弦对弧度的角度进行运算,而矩形的旋转以度表示。

由于补丁程序不会自动设置绘图限制,因此需要对其进行显式设置。

以下是一些入门代码:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
width = 6
height = 4
num_rect = 12
r = width / 2 / np.sin(np.pi / num_rect)
for i in range(num_rect):
    theta = 2 * np.pi * (i + 0.5) / num_rect
    x = r * np.cos(theta)
    y = r * np.sin(theta)
    rectangle = plt.Rectangle((x, y), width, height, angle=360 * i / num_rect - 90,
                              edgecolor='dodgerblue', facecolor=plt.cm.rainbow(i / num_rect), alpha=.5)
    ax.add_patch(rectangle)

d = (r + height) * 1.1
ax.set_xlim(-d, d)
ax.set_ylim(-d, d)
ax.set_aspect('equal')
plt.show()

resulting plot