\[ \newcommand{\pmi}{\operatorname{pmi}} \newcommand{\inner}[2]{\langle{#1}, {#2}\rangle} \newcommand{\Pb}{\operatorname{Pr}} \newcommand{\E}{\mathbb{E}} \newcommand{\RR}{\mathbf{R}} \newcommand{\script}[1]{\mathcal{#1}} \newcommand{\argmin}[2]{\underset{#1}{\operatorname{argmin}} {#2}} \newcommand{\optmin}[3]{ \begin{align*} & \underset{#1}{\text{minimize}} & & #2 \\ & \text{subject to} & & #3 \end{align*} } \newcommand{\optmax}[3]{ \begin{align*} & \underset{#1}{\text{maximize}} & & #2 \\ & \text{subject to} & & #3 \end{align*} } \newcommand{\optfind}[2]{ \begin{align*} & {\text{find}} & & #1 \\ & \text{subject to} & & #2 \end{align*} } \]
I recently had a small visualization that I wanted to do: Given a 3D stack of images, plot them with the ability to interactively flip through the stack. Also, I wanted to have it work on a static site like Github Pages (e.g. this site).
This seemed to me like a reasonable expectation of any good programming language, especially the most popular data science language. There’s certainly others asking the same questions as me, and years of talk of making this easy to do. Note that my search was geared specifically towards images and geospatial data; if I just wanted some bar charts with sliders, I would have stuck with the embedding functionality of something like Altair (or one of the other 5 options below).
Turns out that my decision to stick with Python only and avoid Javascript made this into quite the scavenger hunt. You can see below how many Python plotting libraries it took before I found what I wanted. This isn’t trying to be a full comparison of the libraries (I have no desire to do that). I only hope that I’ll get to spare somebody else the tedium of trying 15 plotting demos.
Skipping to the winners, here were my favorites:
Here’s the notes I made about the others attempted along the way, and why they didn’t work for my case (if I missed something obvious and easy here, I’d be happy to hear how).
For the two winners, I’ll show what I was able to accomplish with just a few lines of code. Hopefully it’s easy enough to translate to any other 3D image stack.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from numpy.fft import fft2, ifft2, fftshift
%matplotlib notebook
Here I was playing around with creating Gaussian random fields. These are used in cosmology to describe the distribution of stars/galaxies in the universe, but also work as a way to simulate turbulence in the atmosphere (my use case).
Theres a relatively simple way and fast way to generate an instance of this random field:
def power_law(k, beta):
# condition, true replacement, false replacement
with np.errstate(divide="ignore"):
return np.where(k > 0, k ** (-beta), 0.0)
def make_gaussian_field(Nsize, beta=3, seed=None):
if seed is not None:
np.random.seed(seed)
white_noise = np.random.uniform(size=(Nsize, Nsize))
w_hat = fft2(white_noise)
idxs = np.concatenate((np.arange(Nsize / 2 + 1), np.arange(-Nsize / 2 + 1, 0)))
ka = 2 * np.pi / Nsize * idxs[:, np.newaxis]
karr = np.sqrt(ka ** 2 + ka.T ** 2)
P = np.sqrt(power_law(karr, beta))
Phi = w_hat * P
return ifft2(Phi).real
I wanted to try and see how the $\beta$ parameter affected the generated noise visually, so I made a stack of these with increasing $\beta$:
beta_range = np.arange(0, 3.5, 0.5)
phi_stack = np.array([make_gaussian_field(100, beta, seed=0) for beta in beta_range])
print(f"Image stack: {phi_stack.shape = }")
Image stack: phi_stack.shape = (7, 100, 100)
Plotting one of these images is easy enough with Matplotlib:
plt.close()
fig, ax = plt.subplots()
phi = phi_stack[-1]
axim = ax.imshow(phi)
fig.colorbar(axim, ax=ax)
plt.axis("off")
plt.show()
<IPython.core.display.Javascript object>
Now here’s the result of my search on how to visualize the entire stack.
For viewing one image at a time and flipping through with a slider, HoloViews
seems to have the nicest interface.
import holoviews as hv
from holoviews import opts
import xarray as xr
hv.extension("bokeh", "matplotlib")
# Example options from their quick start guide
opts.defaults(
opts.GridSpace(shared_xaxis=True, shared_yaxis=True),
opts.Image(cmap="viridis", width=400, height=400),
opts.Labels(
text_color="white",
text_font_size="8pt",
text_align="left",
text_baseline="bottom",
),
opts.Path(color="white"),
opts.Spread(width=600),
opts.Overlay(show_legend=False),
)
I started by labelling my stack so I could convert it into an xarray dataset.
# Make a subset that is uneven so you can distiguish the dimensions:
p1 = phi_stack[:, :-10, :-20]
print(p1.shape)
xrphi = xr.Dataset(
data_vars={"phi": (["beta", "y", "x"], p1)},
coords={
"beta": beta_range,
"y": np.arange(p1.shape[1]),
"x": np.arange(p1.shape[2]),
},
)
xrphi
(7, 90, 80)
<xarray.Dataset> Dimensions: (beta: 7, x: 80, y: 90) Coordinates: * beta (beta) float64 0.0 0.5 1.0 1.5 2.0 2.5 3.0 * y (y) int64 0 1 2 3 4 5 6 7 8 9 10 ... 80 81 82 83 84 85 86 87 88 89 * x (x) int64 0 1 2 3 4 5 6 7 8 9 10 ... 70 71 72 73 74 75 76 77 78 79 Data variables: phi (beta, y, x) float64 0.05235 0.2187 0.1063 ... 0.9273 0.5682 0.4145
array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. ])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79])
array([[[ 5.23546123e-02, 2.18730475e-01, 1.06304484e-01, ..., -3.76262330e-01, -2.00318694e-01, -3.77731173e-01], [ 1.81357645e-01, -2.26450918e-01, 2.38735131e-01, ..., 4.31622402e-01, 2.07955510e-01, -4.64619962e-01], [-1.84663010e-01, 1.99884597e-01, -1.18707052e-01, ..., 3.02743696e-01, 1.33989045e-01, 3.77829075e-01], ..., [ 3.96388452e-01, 4.30547893e-01, 2.84458248e-01, ..., -1.10181522e-01, 3.44750313e-01, 1.40989680e-01], [ 1.45129774e-01, -3.39342759e-01, -1.94492635e-01, ..., -2.17752938e-01, -5.99595992e-02, 2.68557978e-01], [-3.62052857e-01, 1.08849519e-01, 3.86346526e-01, ..., 3.46018819e-01, -4.02979822e-01, -3.85036485e-01]], [[ 5.01040493e-02, 1.78270274e-01, 1.13298902e-01, ..., -2.90187893e-01, -1.58040890e-01, -3.06972591e-01], [ 1.34326486e-01, -1.55810209e-01, 2.02100651e-01, ..., 3.87527396e-01, 1.94468585e-01, -3.66719724e-01], [-1.10271448e-01, 1.55638294e-01, -1.04164145e-01, ..., 3.46428097e-01, 1.86087562e-01, 3.27066622e-01], ... [ 1.57003548e-01, 2.20158909e-01, 1.67525229e-01, ..., 4.17190084e-01, 4.92855402e-01, 3.66510256e-01], [-1.94950986e-02, -1.06841956e-01, -4.74422690e-02, ..., 3.34465089e-01, 3.18039999e-01, 3.33452635e-01], [-2.41727504e-01, -7.05887545e-02, 2.37082023e-02, ..., 5.60394337e-01, 1.85566852e-01, 6.68797002e-02]], [[-2.99899239e-02, 1.02670578e-02, -3.06107467e-04, ..., 1.21456291e+00, 1.22004166e+00, 1.11762691e+00], [-1.37765598e-02, -7.98067124e-02, -3.02668599e-02, ..., 1.61278336e+00, 1.47042255e+00, 1.17670873e+00], [-1.88502867e-02, -2.33545237e-02, -2.01150490e-01, ..., 1.82771748e+00, 1.66084660e+00, 1.52541815e+00], ..., [ 1.04243804e-01, 1.57562162e-01, 1.03288623e-01, ..., 7.46717416e-01, 7.65442854e-01, 6.12751416e-01], [-8.49285039e-02, -1.44813390e-01, -1.02925463e-01, ..., 7.06796082e-01, 6.46306523e-01, 6.05660746e-01], [-3.10993300e-01, -1.65505827e-01, -9.04343752e-02, ..., 9.27330139e-01, 5.68155200e-01, 4.14475808e-01]]])
This is an xarray
dataset, but HoloViews needs its own hv.Dataset
.
Luckily, it’s integrated well-enough with xarray that you can just pass it in to create it:
phids = hv.Dataset(xrphi)
To visualize this, you create an Image
object.
The only extra information you need to pass to the Image
constructor is the kdims
, or the “Key” dimenions: which is the x (horizontal) dimension, and which is the y (vertical). The other dimensions will get gobbled up and become a slider on the “HoloMap”.
If you’ve got two dimensions named ‘x’ and ‘y’, it will interpret this automatically (but being explicit is nice):
imnoise = phids.to(hv.Image, kdims=["x", "y"])
imnoise
This is what I was looking for! It’s especially nice given how few lines of code it took. Flipping through the slider, we see that the simulated noise goes from pure white noise (when $\beta = 0$) to very spatially correlated, realistic looking tropospheric noise at high $\beta$s.
BUT, the final test was whether it was easy to output an HTML snippet that will work offline, or whether that’s another huge obstacle.
Luckily, it was this simple:
outname = "test_holo.html"
renderer = hv.renderer("bokeh")
# Unclear why the function must append .html? oh well
renderer.save(imnoise, outname.replace(".html", ""))
from IPython.core.display import HTML
# Now we can load it here, or insert it anywhere as an embedding:
with open(outname) as f:
wt = f.read()
HTML(wt)
Though it took many hours of search and trying different library examples, I was sold after I found this.
It was exactly what I wanted, looked nice, needed very few lines of code, and the integration with xarray
is an added bonus.
They even have a further extension for other geospatial data with GeoViews, which I’ll keep my eye on for more complicated map making.
While my use case here is definitely better as a 2D slider, I originally wanted to see it as a 3D surface.
import ipyvolume as ipv
from ipywidgets import VBox
Kx, Ky = np.meshgrid(np.arange(phi_stack.shape[2]), np.arange(phi_stack.shape[1]))
# Make a colormap proportional to height
colormap = cm.coolwarm
znorm = phi - phi.min()
znorm /= znorm.ptp()
znorm.min(), znorm.max()
color = colormap(znorm)
Ipyvolume made this nearly as easy as using Matplotlib’s 3D plotting, but it has a much sleeker interface thanks to the other JS libraries it uses.
ipv.figure()
mesh = ipv.plot_surface(Kx, Ky, phi_stack, color=color[..., :3])
ipv.animation_control(mesh) # shows controls for animation controls
vb = VBox([ipv.gcc()])
vb
In a live Jupyter kernel, this is how you would plot it. But, like HoloViews, ipyvolume also makes it easy to save as an HTML embedding:
outname = "widget1.html"
ipv.embed.embed_html(outname, [vb])
# Now load the snippet we just saved to show it works as a standalone
with open(outname) as f:
wt = f.read()
HTML(wt)
While the animation is pretty sweet, I think I was a bit over eager in thinking this example needed to be 3D… maybe next time.