numpy-ndarraycolormap

How to fix a colormap so that it is not relative?


I want to plot binary arrays (filled with zeros or ones). I am using the default colormap viridis, so I expected the full-zero arrays to be all purple, and the full-one arrays to be all yellow, BUT every time an array has the same value everywhere (only ones OR only zeros), it appears all purple. How can I "fix" the colormap so that "ones" appear yellow and "zeros" appear purple, independently of the rest of the array ?

I tried "binarizing" the colormap with the line : new_colormap = mpl.colormaps['viridis'].resampled(2) but it didn't change anything


Solution

  • You need to set explicit color bounds for your colormap. This ensures that specific values map consistently to the same colors, regardless of the data range in the array.

    Here's how you can achieve this:

    Import the necessary libraries:

    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    

    Create a colormap with fixed boundaries:

    # Define boundaries for your colormap
    boundaries = [0, 0.5, 1]
    
    # Create a colormap that is fixed from 0 to 1, with 0 mapped to the first color of 'viridis'
    # and 1 mapped to the last color of 'viridis'
    fixed_cmap = plt.cm.colors.ListedColormap(
        [plt.cm.viridis.colors[0], plt.cm.viridis.colors[-1]], 'indexed', len(boundaries) - 1
    )
    
    # Create a Normalize object which will scale data between 0 to 1
    norm = mcolors.BoundaryNorm(boundaries, fixed_cmap.N, clip=True)
    Use this colormap and norm in your plot:
    
    # Example binary data
    data = [[1, 1, 0, 0], [0, 0, 1, 1]]
    
    plt.imshow(data, cmap=fixed_cmap, norm=norm)
    plt.colorbar()
    plt.show()
    

    This code sets up a colormap that has only two colors: the first and last colors of the 'viridis' colormap, corresponding to the values 0 and 1, respectively. The BoundaryNorm object ensures that these colors are used for values in the specified boundaries (0 to 0.5 for the first color, 0.5 to 1 for the second color).

    When you plot your binary array with this setup, zeros should appear as purple (the first color in 'viridis') and ones as yellow (the last color in 'viridis'), regardless of the array's overall data composition.