Matplotlib - 填充螺旋線



一般定義中,螺旋線是一種幾何曲線,它從中心點發出,並隨著繞中心點旋轉而逐漸遠離。螺旋線呈現螺旋狀圖案,並有多種形式,包括阿基米德螺旋線和對數螺旋線。請參見下圖作為參考:

Fill Spiral_intro

另一方面,填充螺旋線是指螺旋曲線的視覺化表示,其中螺旋線包圍的空間填充了顏色或圖案。

在本教程中,我們將看到使用 Matplotlib 建立和填充螺旋線的兩種不同方法。該過程包括定義表示螺旋線的數學方程,然後使用諸如pyplot.fill()之類的函式為螺旋線包圍的區域著色。

建立基本的填充螺旋線

可以使用引數方程在極座標中定義基本的填充螺旋線。然後使用pyplot.fill()函式用顏色填充螺旋線包圍的區域。

示例

這是一個使用pyplot.fill()np.concatenate()函式建立基本填充螺旋線的示例。

import matplotlib.pyplot as plt
import numpy as np

# Define parameters
theta = np.radians(np.linspace(0,360*5,1000))
a = 1
b = 0.2

fig, axes = plt.subplots(figsize=(7, 4))

# Create a spiral
for dt in np.arange(0, 2 * np.pi, np.pi / 2.0):
   x = a * np.cos(theta + dt) * np.exp(b * theta)
   y = a * np.sin(theta + dt) * np.exp(b * theta)

   dt = dt + np.pi / 4.0

   x2 = a * np.cos(theta + dt) * np.exp(b * theta)
   y2 = a * np.sin(theta + dt) * np.exp(b * theta)

   # Concatenate points for filling
   xf = np.concatenate((x, x2[::-1]))
   yf = np.concatenate((y, y2[::-1]))

   # Fill the spiral
   plt.fill(xf, yf)

# Display the plot
plt.show()

輸出

執行上述程式碼後,我們將獲得以下輸出:

fill_spiral_ex1

建立對數填充螺旋線

對數螺旋線是一種特殊的螺旋線,其半徑隨角度呈指數增長。

示例

此示例將對數螺旋線分成幾部分構建,將具有不同引數的線段組合在一起。

import matplotlib.pyplot as plt
import numpy as np

# Define parameters for the logarithmic spiral
a = 2
b = 0.2

# Generate theta and radius values for different pieces
theta1 = np.linspace(0, np.pi * 3.0, 1000, endpoint=True)
r1 = np.exp(b * theta1) * a

theta2 = np.linspace(np.pi, np.pi * 4.0, 1000, endpoint=True)
r2 = np.exp(b * theta1) * a

theta3 = np.linspace(np.pi, 0, 1000)
r3 = r1[-1] * np.ones_like(theta3)

theta4 = np.linspace(np.pi, 2 * np.pi, 1000)
r4 = a * np.ones_like(theta4)

theta5 = np.linspace(np.pi, 2 * np.pi, 1000)
r5 = r1[-1] * np.ones_like(theta5)

theta6 = np.linspace(0, np.pi, 1000)
r6 = a * np.ones_like(theta6)

# Concatenate pieces for filling
theta_final_red = np.concatenate([theta1, theta3, np.flip(theta2), theta4])
radius_red = np.concatenate([r1, r3, np.flip(r2), r4])

theta_final_blue = np.concatenate([theta1, theta5, np.flip(theta2), theta6])
radius_blue = np.concatenate([r1, r5, np.flip(r2), r6])

# Plot the filled spirals
fig = plt.figure(figsize=(7,4))
ax = fig.add_subplot(111, projection='polar')
ax.set_rmax(r1[-1])
ax.fill(theta_final_red, radius_red, "g")
ax.fill(theta_final_blue, radius_blue, "r")

# Plot the individual pieces
ax.plot(theta1, r1)
ax.plot(theta2, r2)

# Black inner circle
theta_inner = np.linspace(0, np.pi * 2.0, 1000, endpoint=True)
r_inner = [a] * len(theta_inner)
ax.fill(theta_inner, r_inner, c='black')

ax.axis(False)
ax.grid(False)

# Display the plot
plt.show()

輸出

執行上述程式碼後,我們將獲得以下輸出:

fill_spiral_ex2
廣告