Search code examples
pythonnumpymatplotlibfft

Plot Square Wave in Python


Im currently working on graphing a square wave in python using numpy and pylot. How would I plot a square wave function over multiple periods of T?

I currently have:

from scipy import signal
import numpy as np
from scipy.fftpack import fft

#Initialize Parameters
p_0 = 2
A = np.sqrt(1/(2*p_0))
t = [-A,A]


plt.plot(t,[A,A])
plt.show()

which just gives me a straight line. The end game is to take the Fourier transform of the square wave function


Solution

  • You could use the square function from scipy.signal

    from scipy import signal
    import matplotlib.pyplot as plt
    t = np.linspace(0, 1, 500, endpoint=False)
    plt.plot(t, signal.square(2 * np.pi * 5 * t),'b')
    plt.ylim(-2, 2)
    plt.grid()
    plt.show()
    
    

    enter image description here