Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: binary heat plot

Let's say I have a 10x10 matrix, that is comprised or just 0s and 1s, represented as a list of lists. How could I use matplotlib to represent such a matrix as a grid of red and black squares? (red for 1, black for 0).

I've search extensively, but the closest I could find was Plot a black-and-white binary map in matplotlib, but the colors are floats less than 1. Once I get 1s in the data, the plot goes awry. Can anyone help? Or point to specific matplotlib documentation that would help me overcome this?

like image 831
wmnorth Avatar asked Oct 28 '25 09:10

wmnorth


1 Answers

You need what's known as a ListedColorMap:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# random data
x = np.random.random_integers(0, 1, (10, 10))

fig, ax = plt.subplots()

# define the colors
cmap = mpl.colors.ListedColormap(['r', 'k'])

# create a normalize object the describes the limits of
# each color
bounds = [0., 0.5, 1.]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# plot it
ax.imshow(x, interpolation='none', cmap=cmap, norm=norm)

enter image description here

like image 63
Paul H Avatar answered Oct 31 '25 12:10

Paul H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!