scipy.signal.find_peaks 的值错误

ValueError with scipy.signal.find_peaks

现在我正在努力绘制应该显示我的数据集峰值的图表,但看起来 find_peaks 函数正在切断不适合峰值的每个数据点检测。 有人知道我如何通过替换不适合零的数据点或者是否有任何其他可能性来绘制图表?

我收到以下错误消息:

ValueError: x and y must have same first dimension, but have shapes (800,) and (105,)

def plot():
    i = 1
    d_time, d_x, d_y, d_z = [], [], [], []
    columns = ["Time", "y", "x", "z"]
    df = pd.read_csv("mydata.csv", usecols=columns)
    for zeile in df.Time:
        if i % 30 == 0:
            d_time.append(df.Time[i])
            d_x.append(df.x[i])
            d_y.append(df.y[i])
            d_z.append(df.z[i])
            i += 1
        elif i > 24000:
            break
        else:
            i += 1

    fig = plt.figure(dpi=64, figsize=(100, 60))

    p_z, _ = scipy.signal.find_peaks(d_z, 0, distance=5)

    plt.plot(d_time, d_z, c='red', label="Z-Achse")
    plt.plot(d_time, p_z, "x", c='blue', label="Peaks Z-Achse")

    plt.title("Peak Detection", fontsize=16)
    plt.xlabel('t(s)', fontsize=16)

    fig.autofmt_xdate()
    plt.ylabel("a(m/s²)", fontsize=16)
    plt.tick_params(axis='both', which='major')

    plt.legend()
    plt.show()


plot()

Link 至 Mydata.csv: https://cdn.discordapp.com/attachments/635516210473336844/945630182415405106/mydata.csv

您的问题在于(正如您也提到的)p_z 削减了很多点,因此 d_timep_z 的长度不同。因此,您会收到错误消息。您可以做的是创建一个等于 d_time 长度的 np.linspace 并使用新的时间向量绘制它。以下是我的解决方案:

import matplotlib.pyplot as plt
import pandas as pd
from scipy import signal
import numpy as np

def plot():
        i=1
        d_time, d_x, d_y, d_z = [], [], [], []
        columns = ["Time", "y", "x", "z"]
        df = pd.read_csv("mydata.csv", usecols = columns)
        for zeile in df.Time:
            if i % 30 == 0:
                d_time.append(df.Time[i])
                d_x.append(df.x[i])
                d_y.append(df.y[i])
                d_z.append(df.z[i])
                i+=1
            elif i > 24000:
                break
            else:
                i+=1


        fig = plt.figure(dpi=64, figsize=(100, 60))

        p_z, _ = signal.find_peaks(d_z, 0, distance=5)

        new_time = np.linspace(d_time[0], d_time[-1], len(p_z))
        plt.plot(d_time, d_z, c='red', label = "Z-Achse")
        # plt.plot(d_time, p_z, "x", c='blue', label = "Peaks Z-Achse")
        plt.plot(new_time, _['peak_heights'], "x", c='blue', label = "Peaks Z-Achse")

        plt.title("Peak Detection", fontsize=16)
        plt.xlabel('t(s)', fontsize=16)
        plt.yscale("log")

        fig.autofmt_xdate()
        plt.ylabel("a(m/s²)", fontsize=16)
        plt.tick_params(axis='both', which='major')

        plt.legend()
        plt.show()
plot()

正如您在第 28 行中看到的,我创建了一个长度等于 d_time 的新时间向量,它解决了您的问题。此外,我已将 y-axis 更改为对数刻度(第 35 行)以便更好地查看结果。