A Merii
A Merii

Reputation: 594

Displaying Images when hovering over point in Plotly scatter plot in python

I am trying to plot something similar to the gif below using plotly, where an image is displayed when hovering on a point in the scatter plot, but I just don't know where to start. Is it even possible to use plotly or will I have to use Bokeh?

Image appearing on hovering in scatterplot

Upvotes: 10

Views: 3304

Answers (1)

rftr
rftr

Reputation: 1275

With Dash 2.0 this can be achieved by the dcc.Tooltip component setting the attributes show (whether the tooltip is shown), bbox (bounding box coordinates) and children (content of the tooltip including the image).

If you take a look at the examples from the dcc.Tooltip documentation, you will notice some key points:

  • Turn off the hover effects from native plotly.js in your figure:
# Assuming fig is your plotly figure
fig.update_traces(hoverinfo="none", hovertemplate=None)
  • The callback is triggered by the hoverData attribute of dcc.Graph that includes the figure and outputs the above described show, bbox and children:
# Assuming app is your Dash app
@app.callback(Output("graph-tooltip", "show"), Output("graph-tooltip", "bbox"),
              Output("graph-tooltip", "children"), Input("graph-basic-2", "hoverData"),
)
def display_hover(hoverData):
    # ...
    pt = hoverData["points"][0]
    bbox = pt["bbox"]
    # ...
    # img_src is your image, e.g. from URL or b64 encoded
    children = [
        html.Div([
            html.Img(src=img_src, style={"width": "100%"}),
            html.P("Tooltip text"),
        ])
    ]
    return True, bbox, children

Upvotes: 2

Related Questions