Skip to content
Advertisement

plotting n number of equal points in circular direction in python

I am working on the task in which I have to make a circle which is having n number of equal parts. I am provided with centre and radius of the circle which is (0,0) and 4 respectively. To achieve this task, I have written below code,

parts = 36                     # desire number of parts of the circle          
theta_zero = 360/parts
R = 4                          # Radius

x_p = []
y_p = []

n = 0
for n in range(0,36):
    x_p.append(R * math.cos(n*theta_zero))
    y_p.append(R * math.sin(n*theta_zero))

However, after running this code, I got output like below which does not seem a coorect which I am suppose to have.

enter image description here

Kindly let me know what I am doing wrong and give some suggestion of correct code. Thank you

Advertisement

Answer

Aside from the fact that you are generating numbers in degrees and passing them to a function that expects radians, there’s a much simpler and less error-prone method for generating evenly-spaced coordinates:

t0 = np.linspace(0, 2 * np.pi, parts, endpoint=False)
x0 = R * np.cos(t0)
y0 = R * np.sin(t0)

endpoint=False ensures that you end up with 36 partitions rather than 35, since otherwise 0 and 2 * np.pi would overlap.

If you wanted to connect the dots for your circle, you would want the overlap. In that case, you would do

t1 = np.linspace(0, 2 * np.pi, parts + 1)
x1 = R * np.cos(t1)
y1 = R * np.sin(t1)

Here is how you would plot a circle with the 36 sectors delineated:

plt.plot(x1, y1)
plt.plot(np.stack((np.zeros(parts), x0), 0),
         np.stack((np.zeros(parts), y0), 0))

Finally, if you want your circle to look like a circle, you may want to run plt.axis('equal') after plotting.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement