Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a 3D circle in Matplotlib

I am a beginner in Python. I'm trying to plot a circle using matplotlib that has tangent to Z axis. I know how to draw a sphere in 3D but don't know how to draw a circle/ring in 3D plot. Can someone help me with the code? Thanks in advance!

like image 956
Higa Avatar asked Oct 24 '25 03:10

Higa


1 Answers

You need the usual imports, plus the 3D toolkit

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

You need a 3D enabled axes object

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

You need a circle, contained in the plane y-z

theta = np.linspace(0, 2 * np.pi, 201)
y = 10*np.cos(theta)
z = 10*np.sin(theta)

Now we can plot the original circle and, as an example, a number of circles rotated about the z-axis and whose centers are also placed at a fixed distance (equal to the circle's radius) from the z-axis, so that they are tangent to it

for i in range(18):
    phi = i*np.pi/9
    ax.plot(y*np.sin(phi)+10*np.sin(phi),
            y*np.cos(phi)+10*np.cos(phi), z)

eventually we place a vertical axis and a legend

ax.plot((0,0),(0,0), (-10,10), '-k', label='z-axis')
ax.legend()

It's time to see what we got

plt.show()

enter image description here

like image 148
gboffi Avatar answered Oct 26 '25 17:10

gboffi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!