Skip to content

Instantly share code, notes, and snippets.

@raphaeljolivet
Last active Sep 10, 2021
Embed
What would you like to do?
Display dynamically custom HTML on hover / click on a data point of Plotly plot.
from ipywidgets import HTML, VBox
from plotly import graph_objects as go
def interactive_plot(df, fig, template, event="hover") :
"""
Make a plot react on hover or click of a data point and update a HTML preview below it.
**template** Should be a string and contain placeholders like {colname} to be replaced by the value
of the corresponding data row.
"""
html = HTML("")
def update(trace, points, state):
ind = points.point_inds[0]
row = df.loc[ind].to_dict()
html.value = template.format(**row)
fig = go.FigureWidget(data=fig.data, layout=fig.layout)
if event == "hover" :
fig.data[0].on_hover(update)
else :
fig.data[0].on_click(update)
return VBox([fig, html])
@raphaeljolivet
Copy link
Author

raphaeljolivet commented Jul 13, 2021

Example usage (assuming your images are stored locally)

plot = xp.scatter(df, "nb_x", "nb_y")
template="<img src='./img/{id}.png'>"
interactive_plot(df, plot, template)

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment