Search code examples
pythononclickplotlywidget

Get coordinates using on_click and ipwidgets on Plotly


I'm trying to get the coordinates in a list type when clicking some point of the graph. I have this sample code that I got here in stackoverflow, but I'm not able to print the list or access it out of the call-back function, how can I do it?

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])

I want to access the list clicked and use the data, but I can't access it nor print it on console.


Solution

  • All you need to do is to use points object as follows:

    @out.capture()
    def base_click(trace, points, selector):
        global clicked
        clicked.append([points.xs[0],points.ys[0]])
    
    print(clicked)  #<--- outside the function base_click