Created
June 8, 2018 18:26
-
-
Save lucasea777/5587ec1b9111da982a945262cf80a1d8 to your computer and use it in GitHub Desktop.
Pretty print matrix with colors proportional to each value.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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