Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pretty print matrix with colors proportional to each value.
import numpy as np
# https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences
A = np.random.randint(-100, 100, size=(7, 7))
def pformat(A, header=True):
mv = min([min([int(v) for v in row]) for row in A])
Mv = max([max([int(v) for v in row]) for row in A])
f = lambda r, m, M: int(- (255*r)/(m - M) + (255*m)/(m-M))
#c = '\033[38;2;{1};{2};{3};48;2;0;0;0m{0}\033[0m'.format
c = '\033[38;2;{1};{2};{3}m{0}\033[0m'.format
middle = (Mv - mv)/2 + mv
pv = lambda t, v: c(t, 0, f(v, mv, middle), 255) if v <= middle else c(t, 0, 255, 255 - f(v, middle, Mv))
m, text = max([max([len(str(v)) for v in row]) for row in A]), ''
if header:
H = ' '*m + pv(mv, mv)
H += ''.join([pv('=', v) for v in np.linspace(mv, Mv, num=len(A)*(m+2))])
H += pv(Mv, Mv) + ' \n\n\n'
text = H
for l in A:
text += ' '*m
for v in l:
text += ' '*(m-len(str(v))) + pv(v, int(v)) + ' '*3
text += '\n'
return text
print(pformat(A))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment