How to modify a Plotly layout image using custom buttons to show or not an image

I am trying to create two buttons on a plotly graph object to display or not an image but just the trace move not the image. I would like to display or not a background image.
Here the code

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]))
fig.add_layout_image(
    dict(
        source="https://i.imgur.com/ebWhzmj.png",
        xref="paper", yref="paper",
        x=0.5, y=0.5,
        sizex=0.2, sizey=0.2,
        opacity=0.5,
        layer="below")
)
steps = [
    dict(
        method="update",
        args=[{"visible": [False, True]},
              {"title": "No image"}],
        label="No image"
    ),
    dict(
        method="update",
        args=[{"visible": [True, False]},
              {"title": "Image"}],
        label="Image"
    )
]
updatemenu = go.layout.Updatemenu(
    type="buttons",
    direction="down",
    showactive=True,
    buttons=list(steps)
)
fig.update_layout(
    updatemenus=[updatemenu],
    title="Image"
)
fig.show()
fig.write_html("test.html")

@hierophant
To get your button work, first of all you should decide what you intend to change with each button:

  • if only a trace attribute(s), then use the method restyle;
  • if only a layout attribute(s), use the method relayout;
  • if both trace, and layout attributes, use the method update.
    From your code it is obvious that a layout image is added to layout. Hence in the button definitin you will call the method=β€œrelayout”.
help(go.Layout)

lists the layout attributes/properties. Among them is the list images, i.e. we can add more than a single image to a figure layout.
In your case this list contains only an image, as images[0]. For this image a button changes the attribute visible from True to False. Hence the code to make your image visible and invisible is as follows:

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]))
fig.add_layout_image(
    dict(
        source="https://i.imgur.com/ebWhzmj.png",
        xref="paper", yref="paper",
        x=0.5, y=0.5,
        sizex=0.2, sizey=0.2,
        opacity=0.5,
        visible=True, 
        layer="below")
)
buttons = [
    dict(
        method="relayout",
        args=[{"images[0].visible": True},
              {"title": "Image"}],
        label="Image"
    ),
    dict(
        method="relayout",
        args=[{"images[0].visible": False},
              {"title": "No image"}],
        label="No image"
    ),
    
]
updatemenu = go.layout.Updatemenu(
    type="buttons",
    direction="down",
    showactive=True,
    buttons=buttons
)
fig.update_layout(
    updatemenus=[updatemenu],
    title="Image"
)
1 Like