-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) |
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
Example usage (assuming your images are stored locally)