はじめに
毎回忘れて調べるので備忘録兼コピペ用として書きます.
Python を用いて,複素数のデータを入力として,位相及び振幅をプロットします.
環境
- Python 3.11
- numpy 1.26.3
- matplotlib 3.8.3
方法
複素正弦波z
を生成して,プロットする.
必要そうなラベルなどはすでに設定済みなので,適宜変更してください.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,4*np.pi,100)
z = np.exp(1j*x)
r = np.abs(z)
theta = np.angle(z)
fig, ax = plt.subplots(2, 1)
ax[0].plot(r)
ax[0].set_xlabel("time")
ax[0].set_ylabel("amplitude")
_, y_max = ax[0].get_ylim()
ax[0].set_ylim(0,y_max)
ax[1].plot(theta)
ax[1].set_xlabel("time")
ax[1].set_ylabel("angle")
ax[1].set_ylim([-np.pi-0.1,np.pi+0.1])
ax[1].set_yticks([-np.pi, 0, np.pi])
ax[1].set_yticklabels(['-π', '0', 'π'])
plt.tight_layout()
plt.show()
Appendix
位相の連続性に着目したい場合には, np.unwrap()
が便利.
x = np.linspace(0,4*np.pi,100)
z = np.exp(1j*x)
r = np.abs(z)
theta = np.angle(z)
theta_unwrapped = np.unwrap(theta)
fig, ax = plt.subplots(2, 1)
ax[0].plot(r)
ax[0].set_xlabel("time")
ax[0].set_ylabel("amplitude")
_, y_max = ax[0].get_ylim()
ax[0].set_ylim(0,y_max)
ax[1].plot(theta_unwrapped)
ax[1].set_xlabel("time")
ax[1].set_ylabel("angle")
# ax[1].set_ylim([-np.pi-0.1,np.pi+0.1])
# ax[1].set_yticks([-np.pi, 0, np.pi])
# ax[1].set_yticklabels(['-π', '0', 'π'])
plt.tight_layout()
plt.show()
出力結果は以下の通り.
位相の連続性が保たれたままプロットできている.