Warm tip: This article is reproduced from stackoverflow.com, please click
matplotlib python plot 3d

# 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!

Questioner
Higa
Viewed
79 gboffi 2019-07-03 21:58

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 c ircles'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()
`````` 