抑制绘图只获取结果

0 投票
3 回答
1534 浏览
提问于 2025-04-27 13:43

我正在尝试对齐两个信号,以找到能给我最佳系数的延迟。我在使用matplotlib中的xcorr函数。以下代码中,我只对z感兴趣。

有没有办法不显示图表(我不想要图表),只获取结果呢?

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])

谢谢

暂无标签

3 个回答

0

正如我在这里回答的,https://stackoverflow.com/a/47897581/5122657,有时候我们不能使用 numpy.correlate,因为有时我们需要的 maxlags 参数只有 matplotlib.xcorr 提供。但是我明白,如果我们直接把复杂数据类型作为参数传给 matplotlib.xcorr,当 matplotlib 尝试绘图时,会出现“将复杂数据转换为实数数据类型”的警告。下面我修改了 matplotlib 的代码,使其可以作为一个独立的函数使用。

<!-- 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
4

matplotlib 是一个用于绘图的模块。如果你不需要绘图,直接使用 numpy 会更好。你可以查看 numpy.correlate 的文档。

如果你想了解 xcorr 的更多内容,可以使用 inspect.getsource 来查看它的具体实现。下面是一个简化的代码示例:

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
2

使用 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))

撰写回答