Reputation: 2742
I am trying to align two signals to get the lag that gives me the best coefficient. I am using the xcorr
function in matplotlib. I am only interested in z
in the following code.
Is there a way to suppress the plot (I dont want the plot) and get only the result?
from matplotlib.pyplot import xcorr
z = xcorr([1.,2.,3.,4.,5.], [0,0,0,0,1.], normed=False, maxlags=4)
lagsOut = list(z[0])
corrCoeff = list(z[1])
Thanks
Upvotes: 0
Views: 1590
Reputation: 1579
as I answered here, https://stackoverflow.com/a/47897581/5122657
Sometimes we cannot use numpy.correlate
because sometimes we need the maxlags parameter that is only provided by the matplotlib.xcorr
. But I understand that if we put complex data type as the arguments into matplotlib.xcorr
directly, we will get "casting complex to real datatype" warning when matplotlib tries to draw the plot.
Below I modified the code from matplotlib, so it can be used as a standalone function.
<!-- language: python -->
import numpy as np
import matplotlib.pyplot as plt
def xcorr(x, y, maxlags=10):
Nx = len(x)
if Nx != len(y):
raise ValueError('x and y must be equal length')
c = np.correlate(x, y, mode=2)
if maxlags is None:
maxlags = Nx - 1
if maxlags >= Nx or maxlags < 1:
raise ValueError('maxlags must be None or strictly positive < %d' % Nx)
c = c[Nx - 1 - maxlags:Nx + maxlags]
return c
Upvotes: 0
Reputation: 10781
Use np.correlate
:
import numpy as np
x = [1., 2., 3., 4., 5.]
y = [0, 0, 0, 0, 1.]
corrCoef = np.correlate(x, y, 'full')
lagsOut = np.arange(-len(x)+1, len(x))
Upvotes: 2
Reputation: 23322
matplotlib
is a plotting module. If you don't want plotting, you're better off just using numpy
directly. See numpy.correlate
In case you need anything more from xcorr
, you can use inspect.getsource
to see what it does. Here's a abridged dump:
def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,
usevlines=True, maxlags=10, **kwargs):
Nx = len(x)
if Nx != len(y):
raise ValueError('x and y must be equal length')
x = detrend(np.asarray(x))
y = detrend(np.asarray(y))
c = np.correlate(x, y, mode=2)
if normed:
c /= np.sqrt(np.dot(x, x) * np.dot(y, y))
if maxlags is None:
maxlags = Nx - 1
if maxlags >= Nx or maxlags < 1:
raise ValueError('maglags must be None or strictly '
'positive < %d' % Nx)
lags = np.arange(-maxlags, maxlags + 1)
c = c[Nx - 1 - maxlags:Nx + maxlags]
if usevlines:
a = self.vlines(lags, [0], c, **kwargs)
b = self.axhline(**kwargs)
else:
kwargs.setdefault('marker', 'o')
kwargs.setdefault('linestyle', 'None')
a, = self.plot(lags, c, **kwargs)
b = None
return lags, c, a, b
Upvotes: 4