import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, FancyArrowPatch
from matplotlib.animation import FuncAnimation
# 建立一個新圖和兩個座標軸
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
# 設定座標軸的等比例,確保圓圈是正圓
ax1.set_aspect('equal')
ax2.set_aspect('auto')
# 限制座標軸的範圍
ax1.set_xlim(-1.5, 1.5)
ax1.set_ylim(-1.5, 1.5)
ax2.set_xlim(0, 2 * np.pi)
ax2.set_ylim(-1.5, 1.5)
# 設定座標軸標籤
ax1.set_xlabel('X axis')
ax1.set_ylabel('Y axis')
ax2.set_xlabel('Angle (radians)')
ax2.set_ylabel('Amplitude')
# 設定標題
ax1.set_title('Rotating Arrow')
ax2.set_title('Sine Waves')
# 繪製一個圓圈
circle = Circle((0, 0), 1, color='blue', fill=False)
ax1.add_patch(circle)
# 初始化箭頭的引數
arrow = FancyArrowPatch((0, 0), (1, 0), color='red', mutation_scale=20, arrowstyle='->', lw=3)
ax1.add_patch(arrow)
# 初始化正弦波的線
x_data = np.linspace(0, 2 * np.pi, 1000)
line1, = ax2.plot(x_data, np.sin(x_data), 'r-', label='sin(ωt)')
line2, = ax2.plot(x_data, np.sin(x_data + 2 * np.pi / 3), 'g-', label='sin(ωt + 2π/3)')
line3, = ax2.plot(x_data, np.sin(x_data + 4 * np.pi / 3), 'b-', label='sin(ωt + 4π/3)')
# 新增圖例
ax2.legend()
# 初始化角度
angle = 0
# 更新函式,用於動畫
def update(frame):
global angle
angle += 0.05 # 每次旋轉0.05弧度
if angle > 2 * np.pi: # 如果角度超過2π,則重置角度
angle = 0
# 更新箭頭的位置
arrow.set_positions((0, 0), (np.cos(angle), np.sin(angle)))
# 更新正弦波的資料
line1.set_ydata(np.sin(x_data + angle))
line2.set_ydata(np.sin(x_data + angle + 2 * np.pi / 3))
line3.set_ydata(np.sin(x_data + angle + 4 * np.pi / 3))
return arrow, line1, line2, line3
# 建立動畫
ani = FuncAnimation(fig, update, frames=np.arange(0, 360), interval=50, blit=True, repeat=True)
# 顯示圖形
plt.show()