Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: is there a way to save the data of a clicked point in a list?

Tags:

python

plotly

I have a 2D plotly graph with a hover feature. When you hover over each point, the label (e.g. 'image 2, cluster 1') associated with that point appears. I'd like for label to be appended onto an existing list if I were to click on the point (rather than just hover over it). The reason why is that I'd later like to use the data of this point to perform another task. Is there an example online that demonstrates how to do this-- have looked through the documentation but haven't found something for this yet. Thanks!

like image 638
Sofia R Valdez Avatar asked Sep 15 '25 13:09

Sofia R Valdez


1 Answers

You need to use callbacks to perform this type of action (register on_click()). Have defined clicked as a list of clicked points. Demonstrated how this can be achieved with ipwidgets or dash

ipwidgets

import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import ipywidgets as widgets
from pathlib import Path
import json

x = np.random.uniform(-10, 10, size=50)
y = np.sin(x)
clicked = []

# construct figure that has holders for points, interpolated line and final lines
fig = go.FigureWidget(
    [
        go.Scatter(x=x, y=y, mode="markers", name="base_points"),
    ]
)
fig.update_layout(template="simple_white")

out = widgets.Output(layout={"border": "1px solid black"})
out.append_stdout("Output appended with append_stdout\n")

# create our callback function
@out.capture()
def base_click(trace, points, selector):
    global clicked
    clicked.append(points.__dict__)

fig.data[0].on_click(base_click)

widgets.HBox([fig, out])

dash

from jupyter_dash import JupyterDash
import dash
from dash.dependencies import Input, Output, State
import numpy as np
import json

clicked = []

# Build App
app = JupyterDash(__name__)
app.layout = dash.html.Div(
    [
        dash.dcc.Graph(
            id="fig",
            figure=go.Figure(go.Scatter(x=x, y=y, mode="markers", name="base_points")),
        ),
        dash.html.Div(id="debug"),
    ]
)


@app.callback(
    Output("debug", "children"),
    Input("fig", "clickData"),
)
def point_clicked(clickData):
    global clicked
    clicked.append(clickData)

    return json.dumps(clickData)

# Run app and display result inline in the notebook
app.run_server(mode="inline")
like image 120
Rob Raymond Avatar answered Sep 17 '25 04:09

Rob Raymond