4

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?

cel
  • 27,769
  • 16
  • 88
  • 113
wmnorth
  • 247
  • 3
  • 8
  • This question is related: http://stackoverflow.com/questions/9707676/defining-a-discrete-colormap-for-imshow-in-matplotlib/ – cel Feb 14 '15 at 18:16

1 Answers1

9

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

Paul H
  • 59,172
  • 18
  • 144
  • 130
  • 2
    There's also [`from_levels_and_colors`](http://matplotlib.org/api/colors_api.html#matplotlib.colors.from_levels_and_colors)if you want a function that generates the colormap and norm in one shot. E.g. `cmap, norm = from_levels_and_colors([0, 0.5, 1], ['r', 'k'])` – Joe Kington Feb 14 '15 at 18:25
  • @tcaswell - It was added fairly recently (~1.2, I think?). Oddly enough, I thought you were the one who added it, but it looks like it was Phil: https://github.com/matplotlib/matplotlib/commit/c16c3c290eb32c4e8874a0e9cf4946a2b57b5dc3 – Joe Kington Feb 14 '15 at 21:52
  • This works, but the colours were reversed: 1 was black, and 0 was red. I changed the colours in the `cmap` line: `cmap = mpl.colors.ListedColormap(['k', 'r'])` and now it works! – wmnorth Feb 15 '15 at 14:09