Search code examples
pythonmatplotlibcolormap

Creating a color map from a list of RGB colors


I want to create a color map in python similar to this image: enter image description here

but my map only consists of 3 rows and 4 columns. And I want to assign a certain color value to each square using RGB values. I have tried this code

colors=np.array([[0.01, 0.08, 0.01], [0.01, 0.16, 0.01], [0.01, 0.165, 0.01], [0.01, 0.3, 0.01],
                 [0.01, 0.2, 0.01], [0.666, 0.333, 0.01], [0.01, 0.165, 0.01], [0.01, 0.3, 0.01],
                 [0.01, 0.2, 0.01], [0.666, 0.333, 0.01], [0.01, 0.165, 0.01], [0.01, 0.3, 0.01]])


fig, ax=plt.subplots()
ax.imshow(colors)
ax.set_aspect('equal')
plt.show()

but the output does not match my expectations. It seems that with this method I cannot use the RGB values to represent the color for a square. Can anyone help me, please? Thank you!


Solution

  • You have a (12,3) colors array, while you need a (4, 3, 3) image, one RGB color per pixel.

    import numpy as np  # type: ignore
    import matplotlib.pyplot as plt  # type: ignore
    
    colors = np.array(
        [
            # this is the first row
            [
                # these are the 3 pixels in the first row
                [0.01, 0.08, 0.01],
                [0.01, 0.16, 0.01],
                [0.01, 0.165, 0.01],
            ],
            [
                [0.01, 0.3, 0.01],
                [0.01, 0.2, 0.01],
                [0.666, 0.333, 0.01],
            ],
            [
                [0.01, 0.165, 0.01],
                [0.01, 0.3, 0.01],
                [0.01, 0.2, 0.01],
            ],
            # this is the fourth row
            [
                [0.666, 0.333, 0.01],
                [0.01, 0.165, 0.01],
                [0.01, 0.3, 0.01],
            ],
        ]
    )
    print(colors.shape)
    
    
    fig, ax = plt.subplots()
    ax.imshow(colors)
    ax.set_aspect("equal")
    plt.show()
    

    Rearrange the data as you need in rows/columns.