Hướng dẫn plotting signals in python


To get the signal plot, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Get random seed value.
  • Initialize dt for sampling interval and find the sampling frequency.
  • Create random data points for t.
  • To generate noise, get nse, r, cnse and s using numpy.
  • Create a figure and a set of subplots using subplots() method.
  • Set the title of the plot.
  • Plot t and s data points.
  • Set x and y labels.
  • To display the figure, use show() method.

Example

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

np.random.seed(0)

dt = 0.01 # sampling interval
Fs = 1 / dt # sampling frequency
t = np.arange(0, 10, dt)

# generate noise:
nse = np.random.randn(len(t))
r = np.exp(-t / 0.05)
cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
s = 0.1 * np.sin(4 * np.pi * t) + cnse
fig, axs = plt.subplots()
axs.set_title("Signal")
axs.plot(t, s, color='C0')
axs.set_xlabel("Time")
axs.set_ylabel("Amplitude")

plt.show()

Output

Hướng dẫn plotting signals in python

Hướng dẫn plotting signals in python

Updated on 16-Jun-2021 12:09:32

  • Related Questions & Answers
  • How to a plot stem plot in Matplotlib Python?
  • How to plot cdf in Matplotlib in Python?
  • How to plot vectors in Python using Matplotlib?
  • How to plot MFCC in Python using Matplotlib?
  • How to plot magnitude spectrum in Matplotlib in Python?
  • How to plot a density map in Python Matplotlib?
  • How to plot an array in Python using Matplotlib?
  • How to plot a multivariate function in Python Matplotlib?
  • Matplotlib – How to plot the FFT of signal with correct frequencies on the X-axis?
  • How to plot a layered image in Matplotlib in Python?
  • How to plot a phase spectrum in Matplotlib in Python?
  • How to plot 3D graphs using Python Matplotlib?
  • How to save a plot in Seaborn with Python (Matplotlib)?
  • How to plot longitudinal magnitude spectrum in Matplotlib using Python?
  • How to plot an angle spectrum using Matplotlib in Python?

AWe distinguish real and complex signals. A real valued signal x is a mapping from time

to a scalar value x(t). We call x a signal and also denote the signal as x(t).

Nội dung chính

  • Plotting real values signals¶
  • Plotting Complex Valued Signals¶
  • A few special functions¶
  • Exercises¶
  • How do you plot a discrete
  • How do you plot a digital signal in Python?
  • Which command is used for plotting graphs of discrete
  • What does plot () do in Python?

A complex valued signal $x$ is a mapping from

. We can characterize signals by looking at the time domain. Traditionally time is represented as a real value running from

to

. Such signals are called continuous time signals.

When using computers we start to represent signal with a discrete and countable stream of numbers: we call these numbers signal samples. At every time instance

the signal value

is stored in memory. All signal valuess between the sample times are simply ignored. These signals are called discrete time signals.

Plotting real values signals¶

Consider a CT signal

. A real valued CT signal is plotted using the standard ways to plot a function

. Consider the sinusoidal signal

for a short interval of time we can plot this as:
t = np.linspace(-0.02, 0.05, 1000)
plt.plot(t, 325 * np.sin(2*np.pi*50*t));
plt.xlabel('t');
plt.ylabel('x(t)');
plt.title(r'Plot of CT signal \$x(t)=325 \sin(2\pi 50 t)\$');
plt.xlim([-0.02, 0.05]);
#@savefig sineplot.png
plt.show()

(Source code, png, hires.png, pdf)

Evidently the above plot is a lie. You cannot plot a CT signal on a digital device. In Computer Graphics class you have or will learn that a function (signal) is plotted as a chain of straight lines (and even the straight lines are discretized as a set of dots). But it sure looks like a CT signal doesn’t it?

Things are different when we consider a DT signal. Given the values of

for say

to

we could use the same strategy and plot it as we did for the CT signal: just connect the dots $(n, x[n])$. That is done in practice often. However in these notes when dealing with the differences between CT and DT signals we want to stress that a DT signal essentially is just a sequence of numbers. There is no need to think about

in the discrete domain and certainly no need to visualize it.

Therefore a DT signal is plotted as a sequence of vertical bars. A stem plot:

n = np.arange(50);
dt = 0.07/50
x = np.sin(2 * np.pi * 50 * n * dt)
plt.xlabel('n');
plt.ylabel('x[n]');
plt.title(r'Plot of DT signal \$x[n] = 325 \sin(2\pi 50 n \Delta t)\$');
#@savefig dtsineplot.png
plt.stem(n, x);

(Source code, png, hires.png, pdf)

Plotting Complex Valued Signals¶

Now consider the complex valued CT signal:

Plotting such a signal as if it were a real valued signal results in a Python warning that complex numbers are casted to real by discarding the imaginary parts. To see everything we have to plot both the real and imaginary part of the signal.

t = np.linspace(-0.02, 0.05, 1000)
plt.subplot(2,1,1); plt.plot(t, np.exp(2j*np.pi*50*t).real );
plt.xlabel('t');
plt.ylabel('Re x(t)');
plt.title(r'Real part of  \$x(t)=e^{j 100 \pi t}\$');
plt.xlim([-0.02, 0.05]);
plt.subplot(2,1,2); plt.plot(t, np.exp(2j*np.pi*50*t).imag);
plt.xlabel('t');
plt.ylabel('Im x(t)');
plt.title(r'Imaginary part of  \$x(t)=e^{j 100\pi t}\$');
plt.xlim([-0.02, 0.05]);
#@savefig csineplot.png
plt.show()

(Source code, png, hires.png, pdf)

Instead of plotting the real and imaginary part of a complex signal, we can also plot the magnitude and angle of the complex values.

t = np.linspace(-0.02, 0.05, 1000)
plt.subplot(2,1,1); plt.plot(t, np.abs(np.exp(2j*np.pi*50*t)) );
plt.xlabel(r'\$t\$');
plt.ylabel(r'\$|x(t)|\$');
plt.title(r'Absolute value of  \$x(t)=e^{j 100 \pi t}\$');
plt.xlim([-0.02, 0.05]);
plt.subplot(2,1,2);
plt.plot(t, np.angle(np.exp(2j*np.pi*50*t))*360/(2*np.pi));
plt.xlabel('\$t\$');
plt.ylabel(r'\$\angle x(t)\$');
plt.title(r'Phase of \$x(t)=e^{j 100 \pi t}\$');
plt.xlim([-0.02, 0.05]);
#@savefig cabsanglesineplot.png
plt.show()

(Source code, png, hires.png, pdf)

Note that both plots of the complex signal are equivalent. They both do represent the same signal. Also note the seemingly strange behaviour of the phase (angle) plot. It looks quite discontinuous. But it is really not because the phase jumps from +180 degrees to -180 degrees and that is of course the same angle! This phenomenon will be seen quite a lot when plotting the phase of complex signals and functions. It is called phase wrapping. If we would allow angles outside the range from -180 to +180 we could obtain a perfectly straight line (doing just that is called phase unwrapping).

A few special functions¶

In DSP we use some special functions:

1. Constant signal

Constant Function
CTDT

**2. Step function **

A step function is like a light switch which is turned on at t = 0.

Step Function
CTDT

3. Pulse function

The pulse function, also called the impulse function, in DT is easy: everywhere zero except at $n=0$ where the values is

. The DT pulse is written as

.

In CT it is more difficult. The pulse in CT is written as

. It is mathematically defined with the sifting

property:

A usefull way to think about a pulse signal is to consider a signal in which you want to concentrate a finite amount of energy in a short a time interval as possible. Energy in a signal is measured by integrating a signal over a period of time.

onsider for instance the signal $x_a(t)$ defined as:

The total energy in this signal is $1$ (the integral of $x(t)$ over the entire domain). This is true irrespective of the value of $a$. In the limit when $arightarrow0$ the value

but still the total area under the function remains 1. In a sloppy way we may define:

The strange thing thus is that the function value is infinite (well more accurate said it is not well defined) at $t=0$ whereas the integral over the entire domain is finite and equal to 1.

We will see many uses of the pulse function. The translated CT pulse function

is plotted as:
n = np.arange(10);
x = np.zeros_like(n);
x[2]=3;
plt.vlines(n,0,x,'b');
plt.ylim(-1,4);
plt.plot(n,0*n, 'b');
#@savefig pulseplot.png
plt.show();

(Source code, png, hires.png, pdf)

The straight line indicates it is a pulse and the length of the line indicates the total energy.

Pulse Function
CTDT

Exercises¶

Write Python functions to plot signals/functions like the examples above. Plot the following functions:

  • Step function u(t) and u[n]
  • Calculate a series of samples of a sine function of 50 Hz (for example 300 or more). Plot these samples as dots into

a graph and plot the sine as well. Change the number of samples to a lower number. What can you deduce from the result?

How do you plot a discrete

A discrete time signal just means sampling your continuous signal at discrete time intervals. The simplest way this can be done is by increasing your step in n. n = [-5:0.25:5]; y = 5*cos(pi*(n/2)-(pi/2));

How do you plot a digital signal in Python?

MatPlotLib with Python.

Set the figure size and adjust the padding between and around the subplots..

Get random seed value..

Initialize dt for sampling interval and find the sampling frequency..

Create random data points for t..

To generate noise, get nse, r, cnse and s using numpy..

Which command is used for plotting graphs of discrete

It is common to graph a discrete-time signal as dots in a Cartesian coordinate system. This can be done in the Matlab environment by using the stem command.

What does plot () do in Python?

The plot() function is used to draw points (markers) in a diagram. By default, the plot() function draws a line from point to point. The function takes parameters for specifying points in the diagram.