Examples of how to plot a circle in python using matplotlib:
Plot a circle using plot()
To plot a circle a first solution is to use the function plot():
import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2*np.pi, 100)
r = np.sqrt(1.0)
x1 = r*np.cos(theta)
x2 = r*np.sin(theta)
fig, ax = plt.subplots(1)
ax.plot(x1, x2)
ax.set_aspect(1)
plt.xlim(-1.25,1.25)
plt.ylim(-1.25,1.25)
plt.grid(linestyle='--')
plt.title('How to plot a circle with matplotlib ?', fontsize=8)
plt.savefig("plot_circle_matplotlib_01.png", bbox_inches='tight')
plt.show()
Using Matplotlib patches circle
A second solution is to use matplotlib.patches.Circle:
import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.5, color='r')
fig, ax = plt.subplots()
plt.xlim(-1.25,1.25)
plt.ylim(-1.25,1.25)
plt.grid(linestyle='--')
ax.set_aspect(1)
ax.add_artist(circle1)
plt.title('How to plot a circle with matplotlib ?', fontsize=8)
plt.savefig("plot_circle_matplotlib_02.png", bbox_inches='tight')
plt.show()
Plot a circle using the circle equation
Another solution from the circle equation
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1.0, 1.0, 100)
y = np.linspace(-1.0, 1.0, 100)
X, Y = np.meshgrid(x,y)
F = X**2 + Y**2 - 1.0
fig, ax = plt.subplots()
ax.contour(X,Y,F,[0])
ax.set_aspect(1)
plt.title('How to plot a circle with matplotlib ?', fontsize=8)
plt.xlim(-1.25,1.25)
plt.ylim(-1.25,1.25)
plt.grid(linestyle='--')
plt.savefig("plot_circle_matplotlib_03.png", bbox_inches='tight')
plt.show()
References
Links | Site |
---|---|
matplotlib.patches.Circle | matplotlib doc |
plot a circle with pyplot | stackoverflow |
Plot equation showing a circle | stackoverflow |