Visualize a vector of booleans as an image grid of symbols with different colors in python

35 views Asked by At

For teaching purposes in statistics and probability, I want to give a visual representation of various probabilities by an image grid with objects or symbols in different colors in a Jupyter notebook.

For instance, by the following code an pixelwise random image is created.

import numpy as np
from PIL import Image
a = np.random.rand(100, 100)
img = Image.fromarray((a * 255).astype('uint8'), mode='L')
display(img)

boolean array depicted as a black and white image

What I would like to have instead is something like this.

enter image description here

In order to better visualize the connection between sets and probability.

1

There are 1 answers

0
user1491229 On

I can provide 3 solutions to this problem.

A random boolean array will be used throughout this answer.

import numpy as np
N = 10
p = .75
bool_array = np.random.choice(a=[False, True], size=(N, N), p=[p, 1-p])

Solution 1: Character Printing

Inspired by Ehsan

ar = bool_array
chars = np.chararray(ar.shape, unicode=True)
true_char = '██'
false_char = ' '
chars[ar] = true_char
print(np.array2string(chars, separator='', formatter={'str_kind': lambda x: x if x else false_char}))

Solution 2: Using matplotlib

Inspired by P. Camilleri

import matplotlib.pyplot as plt
ar = bool_array
plt.imshow(ar, cmap='hot')
plt.show()

Solution 3: Using mlxtend

Adapted from this webpage

from mlxtend.plotting import heatmap
ar = bool_array
heatmap(ar, figsize=(N, N))
plt.show()

I think heatmaps are the best way to visualize probability. It is even possible to choose intermediate colors to demonstrate conditional probability.