pythonmatplotlibdata-scienceimshow

Python matplotlib - Color code positive and negative values in plot


I have a bunch of samples with shape (1, 104). All samples are integers(positive, negative and 0) which are being used in the imshow function of matplotlib. Below is the function I've created to display them as images.

def show_as_image(sample):
    bitmap = sample.reshape((13, 8))
    plt.figure()
    # this line needs changes.
    plt.imshow(bitmap, cmap='gray', interpolation='nearest')
    plt.colorbar()
    plt.show()

I need to color code the positive and negative values from the sample. PS: Take 0 as positive. How do I change my code?


Solution

  • You could set the normalization of the colorcoding such that it is equally spread between the negative absolute value and positive absolute value of the data. Using a colormap with a light color in the middle can help visualizing how far away from zero the values are.

    import numpy as np
    import matplotlib.pyplot as plt
    
    def show_as_image(sample):
        bitmap = sample.reshape((13, 8))
        maxval = np.max(np.abs([bitmap.min(),bitmap.max()]))
        plt.figure()
        plt.imshow(bitmap, cmap='RdYlGn', interpolation='nearest',
                   vmin=-maxval, vmax=maxval)
        plt.colorbar()
        plt.show()
    
    sample=np.random.randn(1,104)
    show_as_image(sample)
    

    enter image description here

    If instead a binary map is required, you may map positive values to e.g. 1 and negative ones to 0.

    import numpy as np
    import matplotlib.pyplot as plt
    
    def show_as_image(sample):
        bitmap = sample.reshape((13, 8))
        bitmap[bitmap >= 0] = 1
        bitmap[bitmap < 0] = 0
        plt.figure()
        plt.imshow(bitmap, cmap='RdYlGn', interpolation='nearest',
                   vmin=-.1, vmax=1.1)
        plt.show()
    
    sample=np.random.randn(1,104)
    show_as_image(sample)
    

    enter image description here

    In such case the use of a colorbar is probably useless.