Monday 31 October 2022

Multiple imshow on the same plot, with opacity slider

With Plotly, I'd like to display two imshow on the same page, at the same place, with opacity.

This nearly works:

import plotly.express as px, numpy as np
from skimage import io
img = io.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
fig = px.imshow(img)
x = np.random.random((100, 200))
fig2 = px.imshow(x)
fig.show()
fig2.show()

but it displays the two imshow images in two different tabs.

How to display the two "imshow" on the same plot, with an opacity slider for both layers?

For reference, here is the matplotlib equivalent:

import numpy as np, matplotlib.pyplot as plt, matplotlib.widgets as mpwidgets, scipy.misc
x = scipy.misc.face(gray=False)     # shape (768, 1024, 3)
y = np.random.random((100, 133))    # shape (100, 133)
fig, (ax0, ax1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [5, 1]})
OPACITY = 0.5
img0 = ax0.imshow(x, cmap="jet")
img1 = ax0.imshow(y, cmap="jet", alpha=OPACITY, extent=img0.get_extent())
slider0 = mpwidgets.Slider(ax=ax1, label='opacity', valmin=0, valmax=1, valinit=OPACITY)
slider0.on_changed(lambda value: img1.set_alpha(value))
plt.show()


from Multiple imshow on the same plot, with opacity slider

No comments:

Post a Comment