如何在 Matplotlib 中繪製圓
Suraj Joshi
2023年1月30日
Matplotlib
Matplotlib Artist
要在 Matplotlib 中繪製圓,我們可以使用以下任何一種方法:
matplotlib.patches.Circle()方法- 圓方程
- 點的散點圖
在 Matplotlib 中使用 matplotlib.patches.Circle() 方法繪製圓
語法:
matplotlib.patches.Circle((x, y), r=5, **kwargs)
其中,(x, y) 是圓心,r 是半徑,預設值為 5。
我們需要使用 add_artist 方法在軸上新增 Circle,因為 Circle 是 Artist 的子類。
import matplotlib.pyplot as plt
figure, axes = plt.subplots()
draw_circle = plt.Circle((0.5, 0.5), 0.3)
axes.set_aspect(1)
axes.add_artist(draw_circle)
plt.title("Circle")
plt.show()
-method.webp)
要繪製沒有填充顏色的圓,我們應該將 fill 引數設定為 False。
import matplotlib.pyplot as plt
figure, axes = plt.subplots()
draw_circle = plt.Circle((0.5, 0.5), 0.3, fill=False)
axes.set_aspect(1)
axes.add_artist(draw_circle)
plt.title("Circle")
plt.show()
-method-without-filling-color.webp)
通過使用 gcf() 和 gca() 函式將圓快速插入到現有圖中,我們可以使上述程式碼更簡單。
import matplotlib.pyplot as plt
figure, axes = plt.subplots()
draw_circle = plt.Circle((0.5, 0.5), 0.3, fill=False)
plt.gcf().gca().add_artist(draw_circle)
plt.title("Circle")
axes.set_aspect(1)
plt.show()

在 Matplotlib 中用圓方程繪製圓
圓的引數方程
圓的引數方程為 x=r*cos(theta) 和 y=r*sin(theta)。
import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 100)
radius = 0.3
a = radius * np.cos(theta)
b = radius * np.sin(theta)
figure, axes = plt.subplots(1)
axes.plot(a, b)
axes.set_aspect(1)
plt.title("Circle using Parametric Equation")
plt.show()

圓方程的中心半徑形式
我們還可以使用圓方程的中心半徑形式繪製圓。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.5, 0.5, 100)
y = np.linspace(-0.5, 0.5, 100)
a, b = np.meshgrid(x, y)
C = a ** 2 + b ** 2 - 0.2
figure, axes = plt.subplots()
axes.contour(a, b, C, [0])
axes.set_aspect(1)
plt.show()

點的散點圖
我們還可以使用 scatter() 方法在 Matplotlib 中繪製一個圓,並使用 s 引數調整半徑。圓的面積是 pi/4*s。
import matplotlib.pyplot as plt
plt.scatter(0, 0, s=4000)
plt.title("Circle")
plt.xlim(-0.75, 0.75)
plt.ylim(-0.75, 0.75)
plt.show()

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj Joshi
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn