Last active
May 9, 2025 20:41
-
-
Save jesserobertson/0b93657703f13b77bbab5c47482d6259 to your computer and use it in GitHub Desktop.
Making an `imshow` for Bokeh that roughly does what I expect.
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
from bokeh.plotting import figure | |
import inspect | |
def retrieve_name(var): | |
""" | |
Gets the name of var. Does it from the out most frame inner-wards. | |
:param var: variable to get name from. | |
:return: string | |
""" | |
for fi in reversed(inspect.stack()): | |
names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var] | |
if len(names) > 0: | |
return names[0] | |
def imshow(X, pixel_size=50, palette='Viridis256'): | |
""" | |
Show an array as an image | |
:param X: the array to visualise | |
:param pixel_size: roughly how big each pixel is | |
:param palette: the Bokeh palette to use | |
:return: a `bokeh.Figure` object (use `bokeh.io.show` to render) | |
""" | |
p = figure( | |
title=f"Array plot of {retrieve_name(X)}", | |
width=X.shape[1] * pixel_size, | |
height=X.shape[0] * pixel_size | |
) | |
p.image( | |
image=[X], | |
x=[0], y=[0], | |
dw=[X.shape[1]], dh=[X.shape[0]], | |
palette=palette | |
) | |
return p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage
gives this output