Python

Matplotlib Spectrogram

A spectrogram is a graphic representation of wavelengths along time that depicts transmission power at a given point in time. In simple terms, a spectrogram is a representation of sound. It’s also known as voicegrams or voiceprint. The signal levels are represented by a spectrogram, which is displayed in a variety of colors. If the signal’s hue is bright, this indicates the signal’s intensity is strong.

In other terms, the spectrogram’s sampling rate is directly related to the color’s luminance. Short-time Fourier series is used to make the spectrograms. It performs a simple time-varying evaluation of the frequency. The primary idea is to break down the sound wave into little chunks, which are then shown on a plot against duration. The specgram() method has been used with the appropriate arguments for this visual representation.

In this article, we’ll look in detail at how to draw a spectrogram in Python by using the Matplotlib module.

Use plt.specgram() Method

Here, we are going to discuss how to utilize the function plt.specgram() to draw the spectrogram in Python.

import matplotlib.pyplot as plt

import numpy as np

import math

Time_diff = 0.0005

Time_Arr = np.linspace(1, 6, math.ceil(6 / Time_diff))

D = 30*(np.sin(4 * np.pi * Time_Arr))

plt.specgram(D, Fs=8, cmap="rainbow")

plt.title('Figure 1')

plt.xlabel("X-AXIS")

plt.ylabel("Y-AXIS")

plt.show()

Before starting the code, we have to introduce different libraries. Matplotlib.pyplot is used for creating animated or static visualizations. NumPy library provides a large number of quantitative data. And the math library is utilized for carrying out mathematical calculations.

In the subsequent step, we have to state the time interval to take the picture of the produced signal. Now, we initialize an array of values by using the NumPy library. Here, we call the function math.ceil() and the value of time difference is provided as a parameter to this function.

Further, we create a new array that contains the actual data points that we want to be drawn. We employ the sin() method. As a parameter of this function, we multiply the 3 and pi values by the already existing array. The spectrogram is being created by the use of the plt.specgram() method.

Data, frequency, and color of the plot are passed as a parameter of this function. Similarly, we set the title of the x-axis and y-axis by the use of the plt.label() function. In the end, we represent the graph with the help of the plt.show() method.

Draw Spectrogram Having Rainbow Color Scheme

We can create the spectrogram by the use of the plt.specgram() function. And here we can specify the color map by providing the ‘cmap’ argument to the function plt.specgram().

import matplotlib.pyplot as plt

import numpy as np

np.random.seed(9360801)

d_t = 0.0007

time = np.arange(1.0, 30.0, d_t)

sig1 = np.sin(5 * np.pi * 150 * time)

sig2 = 1.4 * np.sin(1.4 * np.pi * 450 * time)

sig2[time <= 11] = sig2[14 <= time] = 0

noise = 0.8 * np.random.random(size = len(time))

a = sig1 + sig2 + noise

NFFT = 620

Fs = int(2.5 / d_t)

plt.specgram(a, Fs = Fs, cmap = "rainbow")

plt.title('Figure 2',

fontsize = 22, fontwe]ight ='normal')

plt.show()

First, we import our libraries which are required for graphic visualizations and quantitative analysis. Now, we apply the random() function of the NumPy library to declare a random data set. We specify the value of the time difference. We take a new variable and declare it with the arrange() method of the NumPy library.

Further, we integrate data for two signals by the use of the sin() method of the NumPy library. We create a new variable for noise by the random() method. Here, we pass the size() function to find the length of the signal of the time interval.

Now, we make a new variable that stores the data of noise and other two signals. In addition to this, we define the value for the length of the segment and sampling frequency. The function plt.specgram() is being called to draw a spectrogram. This function contains three parameters including the data set of the x-axis, sampling frequency, and color of the map.

Just before displaying the graph, we specify the title for the graph by the use of the plt.title() method. Here, we can set the fontsize and fontweight of the title.

Use of NFFT to Draw Spectrogram

In this step, we will create a spectrogram by the use of the NFFT parameter.

import matplotlib.pyplot as plt

import numpy as np

np.random.seed(34984980)

d_t = 0.0006

t = np.arange(1.0, 30.0, d_t)

s_1 = np.sin(3 * np.pi * 200 * t)

s_2 = 3 * np.sin(3 * np.pi * 500 * t)

s_2[t <= 11] = s_2[13 <= t] = 0

n = 0.02 * np.random.random(size=len(t))

b = s_1 + s_2 + n

NFFT = 2056

Fs = int(2.0 / d_t)

fig, (ax1, ax2) = plt.subplots(nrows=2)

ax1.plot(t, b)

Pxx, freqs, bins, im = ax2.specgram(b, NFFT=NFFT, Fs=Fs, noverlap=800)

plt.show()

After integrating the libraries, we have to fix the random state by the use of the random() method. Now, we specify the time difference. Here, its value is 0.0007. Further, we declare the value of time interval by using the arrange( ) function of the NumPy library.

In the next step, we acquire the values of both signal waves with the help of the sin() function. Now, we create a temporary chirp of the second signal. We add the value of noise into the mix by using the random() function. We get the length of the noise wave.

Further, we set the value of NFFT. It holds the number of data sets that are involved in every block. The value for the sampling frequency is also defined. To create graphs, first we create two objects and then we employ the plt.subplots() method. Here, we set the no. of rows as a parameter.

In addition to this, we utilize the specgram() method to draw the spectrogram. Here, we passed the value of overlap as a parameter. This shows the no. of points that are overlapping between chunks. Finally in the end, we have to show the graph by the use of plt.show() function.

Conclusion

We have explained the method to create a spectrogram in Python. We observe the utilization of the specgram() method for this type of visualization. We can specify the color scheme of the spectrogram by passing ‘cmap’ as a parameter to the specgram() function. Further, we obtain the spectrogram having a rainbow color pattern.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content