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
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:
Create a colormap with fixed boundaries:
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.