Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay of two imshow plots on top of each other, with a slider to change the opacity of the layer

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?

enter image description here

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()
like image 588
Basj Avatar asked Nov 16 '25 12:11

Basj


1 Answers

You can re-set the opacity of the overlaying img1 within the update function by img1.set_alpha():

enter image description here

enter image description here

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()
like image 104
MagnusO_O Avatar answered Nov 18 '25 05:11

MagnusO_O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!