Search code examples
pythonmatplotlibcolorbarcolormap

How to make colormaps for this image in python m?


I want to make a colormap used in the attached image colorbar. I could do it MATLAB, however, I can't seem to do it in python. So far I tried the code given below but didn't get the result I was looking for.

img = imread('/path/colorbarimage.png')
colors_from_img = img[:, 0, :]
my_cmap = LinearSegmentedColormap.from_list('my_cmap', colors_from_img, N=651)
y = random_sample((100, 100))
imshow(y, cmap=my_cmap);plt.colorbar()

Solution

  • With img[:, 0, :] you're not picking the correct column in the colorbar image (if indeed colorbarimage.png is the image you linked).

    The following works fine:

    import matplotlib.pyplot as plt
    from matplotlib.colors import LinearSegmentedColormap
    import numpy as np
    
    img = plt.imread('colorbarimage.png')
    
    # to check the selected rectangle:
    cropped_cmap = img[145:799, 70:80, :]
    plt.imshow(cropped_cmap)
    plt.show()
    
    
    colors_from_img = img[145:799, 74, :]
    
    my_cmap = LinearSegmentedColormap.from_list('my_cmap', colors_from_img, N=256)
    
    y = np.random.random_sample((100, 100))
    plt.imshow(y, cmap=my_cmap)
    plt.colorbar()
    plt.show()