pythonarrayssignal-processinginterpolationwavelet

create 2D array from wavelets coefficients using python


I need to create 2D array similar to figure below using coefficients of details of a wavelet transform. I am trying for more than 2 weeks to find how I can do it.

enter image description here

This plot represents coefficients of details of a wavelet transformation at different levels (1, 2, 3,4 and 5).The coefficients of details (cA5,cD5,cD4,cD3,cD2,cD1=coeffs) are a 1D array and each has different size. I want to create 2D array similar to the image using the wavelet coefficients how I can do that?

coeffs = wavedec(data, 'sym5', level=5)
    cA5,cD5,cD4,cD3,cD2,cD1=coeffs    
    for i, ci in enumerate(coeffs):
        plt.imshow(ci.reshape(1, -1), extent=[0, 2000, i + 0.5, i + 1.5], cmap='inferno', aspect='auto', interpolation='nearest')
    plt.ylim(0.5, len(coeffs) + 0.5) 
    plt.yticks(range(1, len(coeffs) + 1), ['cA5', 'cD5', 'cD4', 'cD3', 'cD2', 'cD1'])
    plt.show()

Solution

  • The answer is easier than you might have thought.

    Simply take out plt.show() from your for loop:

    import pywt
    import numpy as np
    import matplotlib.pyplot as plt
    data=np.random.rand(4000)
    coeffs = pywt.wavedec(data, 'sym5', level=5)
    cA5,cD5,cD4,cD3,cD2,cD1=coeffs    
    for i, ci in enumerate(coeffs):
        plt.imshow(ci.reshape(1, -1), extent=[0, 2000, i + 0.5, i + 1.5],     cmap='inferno', aspect='auto', interpolation='nearest')
        plt.ylim(0.5, len(coeffs) + 0.5) 
        plt.yticks(range(1, len(coeffs) + 1), ['cA5', 'cD5', 'cD4', 'cD3', 'cD2', 'cD1'])
    plt.show()
    

    This will allow you to update your figure:

    enter image description here


    EDIT:

    If you leave plt.show() in the loop, it will provide individual plots for each coefficient such as the one below:

    enter image description here

    Citing this introduction to matplotlib:

    One thing to be aware of: the plt.show() command should be used only once per Python session, and is most often seen at the very end of the script. Multiple show() commands can lead to unpredictable backend-dependent behavior, and should mostly be avoided.