enedene - 4 months ago 17

Python Question

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

`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

`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:

I'd like to assign black color to all -1 entries and white to all 0 entries, and I'd like it to be shown on color bar below number one as two discrete colors. Here is an example, my photo editing skills are poor, but it should be clear what I want (color bar should be in scale):

It's not important to me to have a continuous

`jet`

`jet`

For example if value range was from -1 to 1000:

Answer

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()
```

for value ranges, you can convert the values to range index first.

Source (Stackoverflow)

Comments