How can I implement a callback function that reacts to mouseout and restores a default when not hovering over a data point?
I simplified a code snipped from the 'Interactive Visualizations' section of the Plotly|Dash tutorial to illustrate my question. In this example a callback function returns the mouseover information. How do I return a default on mouseout?
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
df = pd.DataFrame({
"x": [1,2,1,2],
"y": [1,2,3,4]
})
fig = px.scatter(df, x="x", y="y")
fig.update_traces(marker_size=20)
app.layout = html.Div([
dcc.Graph(
id='basic-interactions',
figure=fig
),
html.Div([
html.Pre(id='hover-data')
])
])
@app.callback(
Output('hover-data', 'children'),
Input('basic-interactions', 'hoverData'))
def display_hover_data(hoverData):
if hoverData:
return str(hoverData)
else:
return "hover over data point"
if __name__ == '__main__':
app.run_server(debug=True)
You can set the clear_on_unhover property on dcc.Graph:
clear_on_unhover (boolean; default False): If True, clear_on_unhover will clear the hoverData property when the user "unhovers" from a point. If False, then the hoverData property will be equal to the data from the last point that was hovered over.
So change this:
dcc.Graph(id="basic-interactions", figure=fig)
to this:
dcc.Graph(id="basic-interactions", figure=fig, clear_on_unhover=True)
On unhover hoverData will be equal to None, so the callback in the example can stay unchanged. "hover over data point" will be returned on unhover.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With