Reputation: 46493
The code below works to overlay two imshow
plots, and to create a slider which changes the value of the global variable OPACITY
.
Unfortunately, img1.set_data(y); fig.canvas.draw_idle()
doesn't redraw the new opacity.
How to make an overlay of two imshow
plots with a slider to change the opacity of the 2nd layer?
import numpy as np, matplotlib.pyplot as plt, matplotlib.widgets as mpwidgets
OPACITY = 0.5
x = np.random.random((100, 50))
y = np.linspace(0, 0.1, 100*50).reshape((100, 50))
# PLOT
fig, (ax0, ax1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [5, 1]})
img0 = ax0.imshow(x, cmap="jet")
img1 = ax0.imshow(y, cmap="jet", alpha=OPACITY)
def update(value):
global OPACITY
OPACITY = value
print(OPACITY)
img1.set_data(y)
fig.canvas.draw_idle()
slider0 = mpwidgets.Slider(ax=ax1, label='opacity', valmin=0, valmax=1, valinit=OPACITY)
slider0.on_changed(update)
plt.show()
Upvotes: 4
Views: 1362
Reputation: 46493
Based on the accepted answer and the answer from Overlay of two layers of different shapes with Matplotlib, here is a full example with opacity slider + plots of different shapes:
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()
Upvotes: 0
Reputation: 1283
You can re-set the opacity of the overlaying img1
within the update
function by img1.set_alpha()
:
Code:
import numpy as np, matplotlib.pyplot as plt, matplotlib.widgets as mpwidgets
OPACITY = 0.5
x = np.random.random((100, 50))
y = np.linspace(0, 0.1, 100*50).reshape((100, 50))
# PLOT
fig, (ax0, ax1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [5, 1]})
img0 = ax0.imshow(x, cmap="jet")
img1 = ax0.imshow(y, cmap="jet", alpha=OPACITY)
def update(value):
img1.set_alpha(value)
fig.canvas.draw_idle()
slider0 = mpwidgets.Slider(ax=ax1, label='opacity', valmin=0, valmax=1, valinit=OPACITY)
slider0.on_changed(update)
plt.show()
Upvotes: 2