Add separate colors for two (or more) specific values โ€‹โ€‹in the color scheme and color bar.

I want to show the matrix in a color plot and give specific colors to two or more special meanings.

import numpy as np from pylab import * np.random.seed(10) a=np.random.randint(-1,10, size=(5, 5)) print a fig, ax = plt.subplots() mat=ax.matshow(a, cmap=cm.jet, vmin=1, vmax=10) colorbar(mat) show() 

Here are the values โ€‹โ€‹of the matrix a :

 [[ 8 3 -1 0 8] [-1 0 9 7 8] [-1 9 7 5 3] [ 2 -1 3 5 7] [ 9 0 7 3 0]] 

Here is the plot: enter image description here
I would like to assign a black color for all -1 entries and white for all 0 entries, and I would like it to appear in the color bar below number one as two discrete colors. Here is an example, my photo editing skills are bad, but it should be clear what I want (the color scale should be to scale):
enter image description here It is not important for me to have a continuous color map of the jet , I would be pleased with the decision in which my color bar would be discrete and consist, for example, of 10 colors, of which two would be black and white, 8 from the colors of the color map of jet . However, it is important that -1 and 0 have different colors, regardless of what the full range of values โ€‹โ€‹is.
For example, if the range of values โ€‹โ€‹was from -1 to 1000:
enter image description here

+4
source share
2 answers

You can use ListedColormap:

 import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt N = 10 np.random.seed(10) a=np.random.randint(-1, N, size=(5, 5)) print a fig, ax = plt.subplots() colors = [(0.0,0.0,0.0),(1.0,1.0,1.0)] colors.extend(mpl.cm.jet(np.linspace(0, 1, N-1))) cmap = mpl.colors.ListedColormap(colors) mat=ax.matshow(a, cmap=cmap, vmin=-1, vmax=N-1) cax = plt.colorbar(mat, ticks=np.linspace(-0.5, N-1-0.5, N+1)) cax.set_ticklabels(range(-1, N)) plt.show() 

enter image description here

for ranges of values, you can first convert the values โ€‹โ€‹to a range index.

+8
source

In response to @newPyUser comment ...

I think @HYRY's magic happens this way ...

A list consisting of 2 RGB elements, black (color [0]) and white (color [1]) colors = [(0.0,0.0,0.0),(1.0,1.0,1.0)] Then add the rest of the color space to the end a list of 2 elements, that is, values โ€‹โ€‹from 0 to N-1 in increments of 1 colors.extend(mpl.cm.jet(np.linspace(0, 1, N-1))) And finally, build a cmap, defined from -1 to N-1 cmap = mpl.colors.ListedColormap(colors) mat=ax.matshow(a, cmap=cmap, vmin=-1, vmax=N-1) Thus, -1 is displayed on black ( colors [0]), and 0 is displayed on white (colors [1])

0
source

Source: https://habr.com/ru/post/915372/


All Articles