Mc Missile
Mc Missile

Reputation: 735

Python imshow with value specific colormap

I have a 2D array of size 2000x200 that can have N different unique values (about 20-30). I want to be able to imshow this array using a colormap (not linear) that has random colors (eg Set3) that assigns every unique value to a random color. The problem of using Set3 for this purpose is that it assigns a random color for a range of values but not a unique value. An example of the problem is shown below:

enter image description here

Upvotes: 1

Views: 1030

Answers (1)

mashtock
mashtock

Reputation: 400

You can create n colors (in your case 20-30) and then assign each value with a random color. See the following code on how to create n colors and then how to assign each rectangle with a unique color.

import matplotlib.pyplot as plt

def get_cmap(n, name='hsv'):
    '''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct 
    RGB color; the keyword argument name must be a standard mpl colormap name.'''
    return plt.cm.get_cmap(name, n)
def main():
    N = 30
    fig=plt.figure()
    ax=fig.add_subplot(111)   
    plt.axis('scaled')
    ax.set_xlim([ 0, N])
    ax.set_ylim([-0.5, 0.5])
    cmap = get_cmap(N)
    for i in range(N):
        rect = plt.Rectangle((i, -0.5), 1, 1, facecolor=cmap(i))
        ax.add_artist(rect)
    ax.set_yticks([])
    plt.show()

if __name__=='__main__':
    main()

Instead of using for i in range(N) you can do some kind of hash function for each value. Hope that would help you.

Upvotes: 1

Related Questions