Skip to content

Instantly share code, notes, and snippets.

Last active Sep 10, 2021
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(, layout=fig.layout)
if event == "hover" :[0].on_hover(update)
else :[0].on_click(update)
return VBox([fig, html])
Copy link

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)


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