1

I'm given an input of 1/0 matrix. And i want to plot it to look like that: example

The thing is that i have to color all the zeros in blue. but when given a matrix of only ones it also turns into blue. is there a way to make the color "stick" with a specific number?

the code i've used:

cmap = ListedColormap(['b', 'g'])  
matrix=np.array(matrix,dtype=np.uint8) 
plt.imshow(matrix,cmap=cmap)

1 Answer 1

4

You could specify the default number of entries in the colormap using the ListedColormap method as you thought, just set the optional argument N = 2. Also, define the minimum and maximum values for your data in the imshow method with vmin and vmax.

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np

# Random matrix

data_ones = np.random.randint(1, 2, size=(8, 8))
data_both = np.random.randint(0, 2, size=(8, 8))

# Define colormap

cmapmine = ListedColormap(['b', 'w'], N=2)

# Plot matrix

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(data_ones, cmap=cmapmine, vmin=0, vmax=1)
ax1.set_title('Ones')
ax2.imshow(data_both, cmap=cmapmine, vmin=0, vmax=1)
ax2.set_title('Zeros and Ones')
plt.show()

Which plots: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.