python 在Plotly上使用on_click和ipwidgets获取坐标

6rqinv9w  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(350)

当我点击图形中的某个点时,我试图获取列表类型中的坐标。我在stackoverflow中得到了这个示例代码,但是我不能打印列表或者从回调函数中访问它,我该怎么做呢?

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

我想访问单击的列表并使用数据,但我无法访问它,也无法在控制台上打印它。

s2j5cfk0

s2j5cfk01#

您需要做的就是使用points对象,如下所示:

@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

相关问题