Plotting A Square Wave Using Matplotlib, Numpy And Scipy


A square wave is a type of non-sinusoidal waveform that is widely used in electric and digital circuits to show signals. Basically, these circuits use a square wave to represent input and output or on and off. Python provides several ways to plot square waves including Matplotlib, NumPy and Scipy libraries. These libraries offer various built-in methods for data visualization, making it easy to create and customize square wave plots.

Python Program for plotting a Square Wave

Before discussing the example programs, it is necessary to familiarize ourselves with the basics of Matplotlib, NumPy and Scipy libraries.

Matplotlib

It is the oldest and most widely used Python library for plotting. It provides a low-level interface that gives us full control over every aspect of our graphs, such as axes, labels, legends, colors, markers, and so forth. We can also integrate it with other libraries such as NumPy and Pandas to plot data from various sources.

NumPy

It is a powerful Python library that serves to store and manipulate large, multi-dimensional arrays. We will use this package in our example programs to generate random data points for our square wave.

Scipy

The scipy library of Python is used for scientific computation. It provides a collection of in-built modules for various operations such as signal processing, integration, interpolation and many more. We will its built-in method named 'signal.square()' to return a square waveform.

Example 1

The following example illustrates how to plot square waves with grids using matplotlib, numpy and scipy.

Approach

  • First, import the numpy library with reference name 'np' and the pyplot module from the matplotlib library and renames it to plt. Also, from scipy, import the module 'signal'.

  • Next, set the frequency and amplitude to 5 and 1 respectively.

  • Use the built-in method 'arange()' to generate values from 0 to 1 with a step size of 0.001 and store them in axisX variable.

  • Calculate the period that is equal to the reciprocal of the frequency.

  • Now, call the signal.square() method that takes the product of 2 pi, frequency, and axisX as its argument to generate a square wave signal. The returned waveform will be stored in the axisY variable.

  • Then, plot square wave using plot() method with axisX and axisY as its arguments.

  • Provide some additional details such as the x and y-axis labels, title, and grid lines with the help of corresponding built-in methods.

  • In the end, use the 'show()' method to display the plot.

# importing required packages
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
# Setting frequency and amplitude for square wave
frequency = 5
amplitude = 1
# To generate values from 0 to 1 with a step size of 0.001
axisX = np.arange(0, 1, 0.001)
# Generating square wave signal using frequency and amplitude
period = 1.0 / frequency
axisY = amplitude * signal.square(2 * np.pi * frequency * axisX)
# Plotting the square wave with title and labels
plt.plot(axisX, axisY)
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Square Wave Graph')
plt.grid(True)
# to display the final graph
plt.show()

Output

Example 2

In this example, we will demonstrate how to plot a square wave graph with a horizontal line that indicates the midpoint of the wave. To do this, we will modify the code from the previous example by adding an additional line of code where we will use the axhline() method. This method draws a horizontal line at a specified point on the graph.

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
# Setting frequency and amplitude for square wave
frequency = 5
amplitude = 1
# To generate values from 0 to 1 with a step size of 0.001
axisX = np.arange(0, 1, 0.001)
# Generating square wave signal using frequency and amplitude
period = 1.0 / frequency
axisY = amplitude * signal.square(2 * np.pi * frequency * axisX)
# Plotting the square wave with title and labels
plt.plot(axisX, axisY)
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Square Wave Graph')
plt.axhline(y = 0, color = 'r')
# to display the final graph
plt.show()

Output

Example 3

In the following example, we will plot the square wave with both grids and a horizontal line indicating the mid of graph. Here, the x-axis values will be provided by the 'axis' and the y-axis values will be generated by calling 'signal.square'.

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
# To generate values from 0 to 1
axis = np.arange(0, 1, 0.001)
# Plotting the square wave with title and labels
plt.plot(axis, signal.square(2 * np.pi * 5 * axis))
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Square Wave Graph')
plt.axhline(y = 0, color = 'r')
plt.grid(True)
# to display the final graph
plt.show()

Output

Conclusion

In this article, we have plotted three different plots of the square waves using the Matplotlib, NumPy and Scipy libraries. We have used NumPy to generate random data points, Matplotlib to plot the graph and Scipy to create the square waveform.

Updated on: 21-Jul-2023

580 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements