pythonarraystime-seriesspectrogram

convert a time series data into spectrogram


How can I convert a time series data array with frequency of 300HZ into a spectrogram image? (want to do this with python)

([[-127, -162, -197, -229, ... -22 ,-21]] )

shape of the array: (1,9000)


Solution

  • Try this and see if it works for you.

    import numpy as np
    import librosa
    import librosa.display
    import matplotlib.pyplot as plt
    
    # Your time series data array
    data = np.array([[-127, -162, -197, -229, ... -22 ,-21]])
    data = data.reshape(-1)  # Flatten the array to a 1D array
    sampling_rate = 300  # The frequency of your data array (300 Hz)
    
    # Compute the Short-Time Fourier Transform (STFT)
    stft = librosa.stft(data)
    
    # Convert the STFT to a spectrogram (magnitude of STFT)
    spectrogram = np.abs(stft)
    
    # Display the spectrogram as an image
    plt.figure(figsize=(12, 6))
    librosa.display.specshow(librosa.amplitude_to_db(spectrogram, ref=np.max), sr=sampling_rate, x_axis='time', y_axis='log')
    plt.colorbar(format='%+2.0f dB')
    plt.title('Spectrogram')
    plt.tight_layout()
    plt.show()