Search code examples
pythonsignal-processingfrequency-analysis

How to convert x-axis from samples into time (s) and frequency (Hz) with python?


here I have plotted an ecg signal in time-domain and frequency-domain with fft(): time-domain

frequency-domain

but as you can see, the x-axis of both images are still in samples.

I have searched some references how to convert samples into time (s) and frequency (Hz), but it fails, not only the x-axis changes but also the plot shape.

Can you help me to solve this problem? Thank you.


Solution

  • The Code can look like this:

    signal, sample_rate = librosa.load(blues_1)
    max_time = signal.size/sample_rate
    
    time_steps = np.linspace(0, max_time, signal.size)
    plt.figure()
    plt.plot(time_steps, signal)
    plt.xlabel("Time [s]")
    plt.ylabel("Amplitude")
    
    f = np.abs(np.fft.fft(signal))
    freq_steps = np.fft.fftfreq(signal.size, d=1/sample_rate)
    plt.figure()
    plt.plot(freq_steps, f)
    plt.xlabel("Frequency [Hz]")
    plt.ylabel("Amplitude")
    

    Time Domain

    Frequency Domain

    Understandably you can also plot only half of the values in frequency domain.