matplotlib.mlab#

Numerical Python functions written for compatibility with MATLABcommands with the same names. Most numerical Python functions can be found intheNumPy andSciPy libraries. What remains here is code for performingspectral computations and kernel density estimations.

Spectral functions#

cohere

Coherence (normalized cross spectral density)

csd

Cross spectral density using Welch's average periodogram

detrend

Remove the mean or best fit line from an array

psd

Power spectral density using Welch's average periodogram

specgram

Spectrogram (spectrum over segments of time)

complex_spectrum

Return the complex-valued frequency spectrum of a signal

magnitude_spectrum

Return the magnitude of the frequency spectrum of a signal

angle_spectrum

Return the angle (wrapped phase) of the frequency spectrum of a signal

phase_spectrum

Return the phase (unwrapped angle) of the frequency spectrum of a signal

detrend_mean

Remove the mean from a line.

detrend_linear

Remove the best fit line from a line.

detrend_none

Return the original line.

classmatplotlib.mlab.GaussianKDE(dataset,bw_method=None)[source]#

Bases:object

Representation of a kernel-density estimate using Gaussian kernels.

Parameters:
datasetarray-like

Datapoints to estimate from. In case of univariate data this is a 1-Darray, otherwise a 2D array with shape (# of dims, # of data).

bw_method{'scott', 'silverman'} or float or callable, optional

The method used to calculate the estimator bandwidth. If afloat, this will be used directly askde.factor. If acallable, it should take aGaussianKDE instance as onlyparameter and return a float. If None (default), 'scott' is used.

Attributes:
datasetndarray

The dataset passed to the constructor.

dimint

Number of dimensions.

num_dpint

Number of datapoints.

factorfloat

The bandwidth factor, obtained fromcovariance_factor, with whichthe covariance matrix is multiplied.

covariancendarray

The covariance matrix ofdataset, scaled by the calculated bandwidth(kde.factor).

inv_covndarray

The inverse ofcovariance.

Methods

kde.evaluate(points)

(ndarray) Evaluate the estimated pdf on a provided set of points.

kde(points)

(ndarray) Same as kde.evaluate(points)

covariance_factor()[source]#
evaluate(points)[source]#

Evaluate the estimated pdf on a set of points.

Parameters:
points(# of dimensions, # of points)-array

Alternatively, a (# of dimensions,) vector can be passed in andtreated as a single point.

Returns:
(# of points,)-array

The values at each point.

Raises:
ValueErrorif the dimensionality of the input points is different

than the dimensionality of the KDE.

scotts_factor()[source]#
silverman_factor()[source]#
matplotlib.mlab.angle_spectrum(x,Fs=None,window=None,pad_to=None,sides=None)#

Compute the angle of the frequency spectrum (wrapped phase spectrum) ofx.Data is padded to a length ofpad_to and the windowing functionwindow isapplied to the signal.

Parameters:
x1-D array or sequence

Array or sequence containing the data

Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculatethe Fourier frequencies,freqs, in cycles per time unit.

windowcallable or ndarray, default:window_hanning

A function or a vector of lengthNFFT. To create window vectors seewindow_hanning,window_none,numpy.blackman,numpy.hamming,numpy.bartlett,scipy.signal,scipy.signal.get_window, etc. If afunction is passed as the argument, it must take a data segment as anargument and return the windowed version of the segment.

sides{'default', 'onesided', 'twosided'}, optional

Which sides of the spectrum to return. 'default' is one-sided for realdata and two-sided for complex data. 'onesided' forces the return of aone-sided spectrum, while 'twosided' forces two-sided.

pad_toint, optional

The number of points to which the data segment is padded when performingthe FFT. While not increasing the actual resolution of the spectrum (theminimum distance between resolvable peaks), this can give more points inthe plot, allowing for more detail. This corresponds to then parameterin the call tofft. The default is None, which setspad_toequal to the length of the input signal (i.e. no padding).

Returns:
spectrum1-D array

The angle of the frequency spectrum (wrapped phase spectrum).

freqs1-D array

The frequencies corresponding to the elements inspectrum.

See also

psd

Returns the power spectral density.

complex_spectrum

Returns the complex-valued frequency spectrum.

magnitude_spectrum

Returns the absolute value of thecomplex_spectrum.

angle_spectrum

Returns the angle of thecomplex_spectrum.

phase_spectrum

Returns the phase (unwrapped angle) of thecomplex_spectrum.

specgram

Can return the complex spectrum of segments within the signal.

matplotlib.mlab.cohere(x,y,NFFT=256,Fs=2,detrend=<functiondetrend_none>,window=<functionwindow_hanning>,noverlap=0,pad_to=None,sides='default',scale_by_freq=None)[source]#

The coherence betweenx andy. Coherence is the normalizedcross spectral density:

\[C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}\]
Parameters:
x, y

Array or sequence containing the data

Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculatethe Fourier frequencies,freqs, in cycles per time unit.

windowcallable or ndarray, default:window_hanning

A function or a vector of lengthNFFT. To create window vectors seewindow_hanning,window_none,numpy.blackman,numpy.hamming,numpy.bartlett,scipy.signal,scipy.signal.get_window, etc. If afunction is passed as the argument, it must take a data segment as anargument and return the windowed version of the segment.

sides{'default', 'onesided', 'twosided'}, optional

Which sides of the spectrum to return. 'default' is one-sided for realdata and two-sided for complex data. 'onesided' forces the return of aone-sided spectrum, while 'twosided' forces two-sided.

pad_toint, optional

The number of points to which the data segment is padded when performingthe FFT. This can be different fromNFFT, which specifies the numberof data points used. While not increasing the actual resolution of thespectrum (the minimum distance between resolvable peaks), this can givemore points in the plot, allowing for more detail. This corresponds tothen parameter in the call tofft. The default is None,which setspad_to equal toNFFT

NFFTint, default: 256

The number of data points used in each block for the FFT. A power 2 ismost efficient. This shouldNOT be used to get zero padding, or thescaling of the result will be incorrect; usepad_to for this instead.

detrend{'none', 'mean', 'linear'} or callable, default: 'none'

The function applied to each segment before fft-ing, designed to removethe mean or linear trend. Unlike in MATLAB, where thedetrend parameteris a vector, in Matplotlib it is a function. Themlabmodule definesdetrend_none,detrend_mean, anddetrend_linear,but you can use a custom function as well. You can also use a string tochoose one of the functions: 'none' callsdetrend_none. 'mean' callsdetrend_mean. 'linear' callsdetrend_linear.

scale_by_freqbool, default: True

Whether the resulting density values should be scaled by the scalingfrequency, which gives density in units of 1/Hz. This allows forintegration over the returned frequency values. The default is True forMATLAB compatibility.

noverlapint, default: 0 (no overlap)

The number of points of overlap between segments.

Returns:
Cxy1-D array

The coherence vector.

freqs1-D array

The frequencies for the elements inCxy.

See also

psd(),csd()

For information about the methods used to compute\(P_{xy}\),\(P_{xx}\) and\(P_{yy}\).

matplotlib.mlab.complex_spectrum(x,Fs=None,window=None,pad_to=None,sides=None)#

Compute the complex-valued frequency spectrum ofx.Data is padded to a length ofpad_to and the windowing functionwindow isapplied to the signal.

Parameters:
x1-D array or sequence

Array or sequence containing the data

Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculatethe Fourier frequencies,freqs, in cycles per time unit.

windowcallable or ndarray, default:window_hanning

A function or a vector of lengthNFFT. To create window vectors seewindow_hanning,window_none,numpy.blackman,numpy.hamming,numpy.bartlett,scipy.signal,scipy.signal.get_window, etc. If afunction is passed as the argument, it must take a data segment as anargument and return the windowed version of the segment.

sides{'default', 'onesided', 'twosided'}, optional

Which sides of the spectrum to return. 'default' is one-sided for realdata and two-sided for complex data. 'onesided' forces the return of aone-sided spectrum, while 'twosided' forces two-sided.

pad_toint, optional

The number of points to which the data segment is padded when performingthe FFT. While not increasing the actual resolution of the spectrum (theminimum distance between resolvable peaks), this can give more points inthe plot, allowing for more detail. This corresponds to then parameterin the call tofft. The default is None, which setspad_toequal to the length of the input signal (i.e. no padding).

Returns:
spectrum1-D array

The complex-valued frequency spectrum.

freqs1-D array

The frequencies corresponding to the elements inspectrum.

See also

psd

Returns the power spectral density.

complex_spectrum

Returns the complex-valued frequency spectrum.

magnitude_spectrum

Returns the absolute value of thecomplex_spectrum.

angle_spectrum

Returns the angle of thecomplex_spectrum.

phase_spectrum

Returns the phase (unwrapped angle) of thecomplex_spectrum.

specgram

Can return the complex spectrum of segments within the signal.

matplotlib.mlab.csd(x,y,NFFT=None,Fs=None,detrend=None,window=None,noverlap=None,pad_to=None,sides=None,scale_by_freq=None)[source]#

Compute the cross-spectral density.

The cross spectral density\(P_{xy}\) by Welch's averageperiodogram method. The vectorsx andy are divided intoNFFT length segments. Each segment is detrended by functiondetrend and windowed by functionwindow.noverlap givesthe length of the overlap between segments. The product ofthe direct FFTs ofx andy are averaged over each segmentto compute\(P_{xy}\), with a scaling to correct for powerloss due to windowing.

If len(x) <NFFT or len(y) <NFFT, they will be zeropadded toNFFT.

Parameters:
x, y1-D arrays or sequences

Arrays or sequences containing the data

Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculatethe Fourier frequencies,freqs, in cycles per time unit.

windowcallable or ndarray, default:window_hanning

A function or a vector of lengthNFFT. To create window vectors seewindow_hanning,window_none,numpy.blackman,numpy.hamming,numpy.bartlett,scipy.signal,scipy.signal.get_window, etc. If afunction is passed as the argument, it must take a data segment as anargument and return the windowed version of the segment.

sides{'default', 'onesided', 'twosided'}, optional

Which sides of the spectrum to return. 'default' is one-sided for realdata and two-sided for complex data. 'onesided' forces the return of aone-sided spectrum, while 'twosided' forces two-sided.

pad_toint, optional

The number of points to which the data segment is padded when performingthe FFT. This can be different fromNFFT, which specifies the numberof data points used. While not increasing the actual resolution of thespectrum (the minimum distance between resolvable peaks), this can givemore points in the plot, allowing for more detail. This corresponds tothen parameter in the call tofft. The default is None,which setspad_to equal toNFFT

NFFTint, default: 256

The number of data points used in each block for the FFT. A power 2 ismost efficient. This shouldNOT be used to get zero padding, or thescaling of the result will be incorrect; usepad_to for this instead.

detrend{'none', 'mean', 'linear'} or callable, default: 'none'

The function applied to each segment before fft-ing, designed to removethe mean or linear trend. Unlike in MATLAB, where thedetrend parameteris a vector, in Matplotlib it is a function. Themlabmodule definesdetrend_none,detrend_mean, anddetrend_linear,but you can use a custom function as well. You can also use a string tochoose one of the functions: 'none' callsdetrend_none. 'mean' callsdetrend_mean. 'linear' callsdetrend_linear.

scale_by_freqbool, default: True

Whether the resulting density values should be scaled by the scalingfrequency, which gives density in units of 1/Hz. This allows forintegration over the returned frequency values. The default is True forMATLAB compatibility.

noverlapint, default: 0 (no overlap)

The number of points of overlap between segments.

Returns:
Pxy1-D array

The values for the cross spectrum\(P_{xy}\) before scaling (realvalued)

freqs1-D array

The frequencies corresponding to the elements inPxy

See also

psd

equivalent to settingy=x.

References

Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, JohnWiley & Sons (1986)

matplotlib.mlab.detrend(x,key=None,axis=None)[source]#

Returnx with its trend removed.

Parameters:
xarray or sequence

Array or sequence containing the data.

key{'default', 'constant', 'mean', 'linear', 'none'} or function

The detrending algorithm to use. 'default', 'mean', and 'constant' arethe same asdetrend_mean. 'linear' is the same asdetrend_linear.'none' is the same asdetrend_none. The default is 'mean'. See thecorresponding functions for more details regarding the algorithms. Canalso be a function that carries out the detrend operation.

axisint

The axis along which to do the detrending.

See also

detrend_mean

Implementation of the 'mean' algorithm.

detrend_linear

Implementation of the 'linear' algorithm.

detrend_none

Implementation of the 'none' algorithm.

matplotlib.mlab.detrend_linear(y)[source]#

Returnx minus best fit line; 'linear' detrending.

Parameters:
y0-D or 1-D array or sequence

Array or sequence containing the data

See also

detrend_mean

Another detrend algorithm.

detrend_none

Another detrend algorithm.

detrend

A wrapper around all the detrend algorithms.

matplotlib.mlab.detrend_mean(x,axis=None)[source]#

Returnx minus the mean(x).

Parameters:
xarray or sequence

Array or sequence containing the dataCan have any dimensionality

axisint

The axis along which to take the mean. Seenumpy.mean for adescription of this argument.

See also

detrend_linear

Another detrend algorithm.

detrend_none

Another detrend algorithm.

detrend

A wrapper around all the detrend algorithms.

matplotlib.mlab.detrend_none(x,axis=None)[source]#

Returnx: no detrending.

Parameters:
xany object

An object containing the data

axisint

This parameter is ignored.It is included for compatibility with detrend_mean

See also

detrend_mean

Another detrend algorithm.

detrend_linear

Another detrend algorithm.

detrend

A wrapper around all the detrend algorithms.

matplotlib.mlab.magnitude_spectrum(x,Fs=None,window=None,pad_to=None,sides=None)#

Compute the magnitude (absolute value) of the frequency spectrum ofx.Data is padded to a length ofpad_to and the windowing functionwindow isapplied to the signal.

Parameters:
x1-D array or sequence

Array or sequence containing the data

Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculatethe Fourier frequencies,freqs, in cycles per time unit.

windowcallable or ndarray, default:window_hanning

A function or a vector of lengthNFFT. To create window vectors seewindow_hanning,window_none,numpy.blackman,numpy.hamming,numpy.bartlett,scipy.signal,scipy.signal.get_window, etc. If afunction is passed as the argument, it must take a data segment as anargument and return the windowed version of the segment.

sides{'default', 'onesided', 'twosided'}, optional

Which sides of the spectrum to return. 'default' is one-sided for realdata and two-sided for complex data. 'onesided' forces the return of aone-sided spectrum, while 'twosided' forces two-sided.

pad_toint, optional

The number of points to which the data segment is padded when performingthe FFT. While not increasing the actual resolution of the spectrum (theminimum distance between resolvable peaks), this can give more points inthe plot, allowing for more detail. This corresponds to then parameterin the call tofft. The default is None, which setspad_toequal to the length of the input signal (i.e. no padding).

Returns:
spectrum1-D array

The magnitude (absolute value) of the frequency spectrum.

freqs1-D array

The frequencies corresponding to the elements inspectrum.

See also

psd

Returns the power spectral density.

complex_spectrum

Returns the complex-valued frequency spectrum.

magnitude_spectrum

Returns the absolute value of thecomplex_spectrum.

angle_spectrum

Returns the angle of thecomplex_spectrum.

phase_spectrum

Returns the phase (unwrapped angle) of thecomplex_spectrum.

specgram

Can return the complex spectrum of segments within the signal.

matplotlib.mlab.phase_spectrum(x,Fs=None,window=None,pad_to=None,sides=None)#

Compute the phase of the frequency spectrum (unwrapped phase spectrum) ofx.Data is padded to a length ofpad_to and the windowing functionwindow isapplied to the signal.

Parameters:
x1-D array or sequence

Array or sequence containing the data

Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculatethe Fourier frequencies,freqs, in cycles per time unit.

windowcallable or ndarray, default:window_hanning

A function or a vector of lengthNFFT. To create window vectors seewindow_hanning,window_none,numpy.blackman,numpy.hamming,numpy.bartlett,scipy.signal,scipy.signal.get_window, etc. If afunction is passed as the argument, it must take a data segment as anargument and return the windowed version of the segment.

sides{'default', 'onesided', 'twosided'}, optional

Which sides of the spectrum to return. 'default' is one-sided for realdata and two-sided for complex data. 'onesided' forces the return of aone-sided spectrum, while 'twosided' forces two-sided.

pad_toint, optional

The number of points to which the data segment is padded when performingthe FFT. While not increasing the actual resolution of the spectrum (theminimum distance between resolvable peaks), this can give more points inthe plot, allowing for more detail. This corresponds to then parameterin the call tofft. The default is None, which setspad_toequal to the length of the input signal (i.e. no padding).

Returns:
spectrum1-D array

The phase of the frequency spectrum (unwrapped phase spectrum).

freqs1-D array

The frequencies corresponding to the elements inspectrum.

See also

psd

Returns the power spectral density.

complex_spectrum

Returns the complex-valued frequency spectrum.

magnitude_spectrum

Returns the absolute value of thecomplex_spectrum.

angle_spectrum

Returns the angle of thecomplex_spectrum.

phase_spectrum

Returns the phase (unwrapped angle) of thecomplex_spectrum.

specgram

Can return the complex spectrum of segments within the signal.

matplotlib.mlab.psd(x,NFFT=None,Fs=None,detrend=None,window=None,noverlap=None,pad_to=None,sides=None,scale_by_freq=None)[source]#

Compute the power spectral density.

The power spectral density\(P_{xx}\) by Welch's averageperiodogram method. The vectorx is divided intoNFFT lengthsegments. Each segment is detrended by functiondetrend andwindowed by functionwindow.noverlap gives the length ofthe overlap between segments. The\(|\mathrm{fft}(i)|^2\)of each segment\(i\) are averaged to compute\(P_{xx}\).

If len(x) <NFFT, it will be zero padded toNFFT.

Parameters:
x1-D array or sequence

Array or sequence containing the data

Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculatethe Fourier frequencies,freqs, in cycles per time unit.

windowcallable or ndarray, default:window_hanning

A function or a vector of lengthNFFT. To create window vectors seewindow_hanning,window_none,numpy.blackman,numpy.hamming,numpy.bartlett,scipy.signal,scipy.signal.get_window, etc. If afunction is passed as the argument, it must take a data segment as anargument and return the windowed version of the segment.

sides{'default', 'onesided', 'twosided'}, optional

Which sides of the spectrum to return. 'default' is one-sided for realdata and two-sided for complex data. 'onesided' forces the return of aone-sided spectrum, while 'twosided' forces two-sided.

pad_toint, optional

The number of points to which the data segment is padded when performingthe FFT. This can be different fromNFFT, which specifies the numberof data points used. While not increasing the actual resolution of thespectrum (the minimum distance between resolvable peaks), this can givemore points in the plot, allowing for more detail. This corresponds tothen parameter in the call tofft. The default is None,which setspad_to equal toNFFT

NFFTint, default: 256

The number of data points used in each block for the FFT. A power 2 ismost efficient. This shouldNOT be used to get zero padding, or thescaling of the result will be incorrect; usepad_to for this instead.

detrend{'none', 'mean', 'linear'} or callable, default: 'none'

The function applied to each segment before fft-ing, designed to removethe mean or linear trend. Unlike in MATLAB, where thedetrend parameteris a vector, in Matplotlib it is a function. Themlabmodule definesdetrend_none,detrend_mean, anddetrend_linear,but you can use a custom function as well. You can also use a string tochoose one of the functions: 'none' callsdetrend_none. 'mean' callsdetrend_mean. 'linear' callsdetrend_linear.

scale_by_freqbool, default: True

Whether the resulting density values should be scaled by the scalingfrequency, which gives density in units of 1/Hz. This allows forintegration over the returned frequency values. The default is True forMATLAB compatibility.

noverlapint, default: 0 (no overlap)

The number of points of overlap between segments.

Returns:
Pxx1-D array

The values for the power spectrum\(P_{xx}\) (real valued)

freqs1-D array

The frequencies corresponding to the elements inPxx

See also

specgram

specgram differs in the default overlap; in not returning the mean of the segment periodograms; and in returning the times of the segments.

magnitude_spectrum

returns the magnitude spectrum.

csd

returns the spectral density between two signals.

References

Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, JohnWiley & Sons (1986)

matplotlib.mlab.specgram(x,NFFT=None,Fs=None,detrend=None,window=None,noverlap=None,pad_to=None,sides=None,scale_by_freq=None,mode=None)[source]#

Compute a spectrogram.

Compute and plot a spectrogram of data inx. Data are split intoNFFT length segments and the spectrum of each section iscomputed. The windowing functionwindow is applied to eachsegment, and the amount of overlap of each segment isspecified withnoverlap.

Parameters:
xarray-like

1-D array or sequence.

Fsfloat, default: 2

The sampling frequency (samples per time unit). It is used to calculatethe Fourier frequencies,freqs, in cycles per time unit.

windowcallable or ndarray, default:window_hanning

A function or a vector of lengthNFFT. To create window vectors seewindow_hanning,window_none,numpy.blackman,numpy.hamming,numpy.bartlett,scipy.signal,scipy.signal.get_window, etc. If afunction is passed as the argument, it must take a data segment as anargument and return the windowed version of the segment.

sides{'default', 'onesided', 'twosided'}, optional

Which sides of the spectrum to return. 'default' is one-sided for realdata and two-sided for complex data. 'onesided' forces the return of aone-sided spectrum, while 'twosided' forces two-sided.

pad_toint, optional

The number of points to which the data segment is padded when performingthe FFT. This can be different fromNFFT, which specifies the numberof data points used. While not increasing the actual resolution of thespectrum (the minimum distance between resolvable peaks), this can givemore points in the plot, allowing for more detail. This corresponds tothen parameter in the call tofft. The default is None,which setspad_to equal toNFFT

NFFTint, default: 256

The number of data points used in each block for the FFT. A power 2 ismost efficient. This shouldNOT be used to get zero padding, or thescaling of the result will be incorrect; usepad_to for this instead.

detrend{'none', 'mean', 'linear'} or callable, default: 'none'

The function applied to each segment before fft-ing, designed to removethe mean or linear trend. Unlike in MATLAB, where thedetrend parameteris a vector, in Matplotlib it is a function. Themlabmodule definesdetrend_none,detrend_mean, anddetrend_linear,but you can use a custom function as well. You can also use a string tochoose one of the functions: 'none' callsdetrend_none. 'mean' callsdetrend_mean. 'linear' callsdetrend_linear.

scale_by_freqbool, default: True

Whether the resulting density values should be scaled by the scalingfrequency, which gives density in units of 1/Hz. This allows forintegration over the returned frequency values. The default is True forMATLAB compatibility.

noverlapint, default: 128

The number of points of overlap between blocks.

modestr, default: 'psd'
What sort of spectrum to use:
'psd'

Returns the power spectral density.

'complex'

Returns the complex-valued frequency spectrum.

'magnitude'

Returns the magnitude spectrum.

'angle'

Returns the phase spectrum without unwrapping.

'phase'

Returns the phase spectrum with unwrapping.

Returns:
spectrumarray-like

2D array, columns are the periodograms of successive segments.

freqsarray-like

1-D array, frequencies corresponding to the rows inspectrum.

tarray-like

1-D array, the times corresponding to midpoints of segments(i.e the columns inspectrum).

See also

psd

differs in the overlap and in the return values.

complex_spectrum

similar, but with complex valued frequencies.

magnitude_spectrum

similar single segment whenmode is 'magnitude'.

angle_spectrum

similar to single segment whenmode is 'angle'.

phase_spectrum

similar to single segment whenmode is 'phase'.

Notes

detrend andscale_by_freq only apply whenmode is set to 'psd'.

matplotlib.mlab.window_hanning(x)[source]#

Returnx times the Hanning (or Hann) window of len(x).

See also

window_none

Another window algorithm.

matplotlib.mlab.window_none(x)[source]#

No window function; simply returnx.

See also

window_hanning

Another window algorithm.