Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@raphaeljolivet
Last active January 31, 2024 03:01
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphaeljolivet/f076256e589f67c028a6bffaab279601 to your computer and use it in GitHub Desktop.
Save raphaeljolivet/f076256e589f67c028a6bffaab279601 to your computer and use it in GitHub Desktop.
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

@thadd3us
Copy link

This is incredibly helpful, thank you! I hadn't been aware of how to connect ipywidgets, go.FigureWidgets, and Plotly event handlers inside a notebook -- in the past, the only way I'd known to do this was via a Dash App, but this is much simpler. Thank you!

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