How? Slider to control visibility of layout images

Hi,

I am trying to build a slider to display a series of images. I will first show a working script for displaying images without a slider. Then I will present my attempt on getting the Plotly slider to work (unsuccessful). I believe the reason is apparent: The tutorial that I have been referring to, “Sliders | Python | Plotly”, only works on the traces or objects in fig.data, whereas I am trying to modify the visibilities of objects in fig._layout_obj.images.

Thanks,
Fanurs


import plotly.graph_objects as go

img_sources = [
    'https://images.unsplash.com/photo-1482625974755-1fccd66c1ceb?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80',
    'https://images.unsplash.com/photo-1493930251520-c4e958c27b86?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80',
]
width, height = 600, 400

fig = go.Figure()
for src in img_sources:
    fig.add_layout_image(
        source=src,
        xref='x', yref='y',
        x=0, y=height,
        sizex=width, sizey=height,
        sizing='stretch',
        visible=False,
    )
fig._layout_obj.images[0]['visible'] = True

fig.update_layout(
    paper_bgcolor='rgba(255, 255, 255, 0)', plot_bgcolor='rgba(255, 255, 255, 0)',
    width=width, height=height,
    margin=dict(l=0, r=0, b=0, t=0, pad=0),
    xaxis=dict(range=[0, width], showgrid=False, visible=False),
    yaxis=dict(scaleanchor='x', range=[0, height], showgrid=False, visible=False),
)
fig.show()
""">>> Only the first image is displayed."""

But things do not work when I try to add the slider to switch between the two images. The slider appears, but it does not modify the visibilities of the images.

"""Not working"""
steps = []
for i, _ in enumerate(img_sources):
    step = dict(method='update',
                args=[dict(visible=[False] * len(img_sources))],
               )
    step['args'][0]['visible'][i] = True
    steps.append(step)
    
sliders = [dict(
    currentvalue=dict(prefix='Image No.: '),
    steps=steps,
)]

fig.update_layout(sliders=sliders)
fig.show()
""">>> The second image cannot be displayed."""

Instead of controlling loading in all the images and controlling their visibility using the slider, you’ll have an easier time controlling the image to load based on the slider change instead.