Search code examples
pythonmatplotlibpython-2.x

matplotlib color map - predefine mappings to values?


I have an array that I am viewing using imshow(). (imsave() really, but the process should be identical).

I know that the values in the array will be between 0-9 and wonder if it is possible to use cmap to set each output to a specific 'color'. Perhaps by mapping these to a dict?


Solution

  • Just use a ListedColormap.

    As a quick (but ugly) example:

    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    
    cmap = ListedColormap(['red', 'green', 'blue', 'black'], 'indexed')
    
    fig, ax = plt.subplots()
    im = ax.imshow([range(4)], interpolation='none', cmap=cmap)
    fig.colorbar(im)
    plt.show()
    

    enter image description here