Python 带有点击事件的交互式绘图

Python interactive plotting with click events

我目前正在尝试通过 np 引入一些数据,对初始数据进行一些处理,绘制它,然后与我的绘图进行交互。 Plotly 有一个关于如何绘图和更改数据点颜色的教程(在 jupyter 中使用点击事件 https://plotly.com/python/click-events/)。我希望做的是能够在 2 个点上单击 click 事件,然后在所选点之间创建一条线并收集我的线位置。我在 plotly 中发现的唯一一件事就是将鼠标悬停在数据上,但无法进行此处理。有没有更好的方法而不是使用 plotly? plotly 上的文档建议只使用破折号,但我还没有找到使用破折号执行此操作的方法。后续问题是,如果我导出我的绘图 (fig.write_html),我如何获取这些数据?

我的样本是:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

# Import libraries
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go


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

fig=go.FigureWidget([go.Scatter(x=x, y=y, mode='markers')])

fig.update_layout(template='simple_white')

scatter=fig.data[0]
colors=['#a3a7e4']*100
scatter.marker.color=colors
scatter.marker.size=[10]*100
fig.layout.hovermode='closest'

fig.update_traces(marker=dict(line=dict(color='DarkSlateGrey')))

# create our callback function
def update_point(trace, points, selector):
    c = list(scatter.marker.color)
    s = list(scatter.marker.size)
    for i in points.point_inds:
        c[i]='#bae2be'
        s[i]=20
        with fig.batch_update():
            scatter.marker.color=c
            scatter.marker.size=s

scatter.on_click(update_point)

fig
  • 假设你尝试的例子是 ipwidgets 我已经扩展了这个
  • 创建一个将作为行目标的空轨迹
  • 用于调试创建 widgets.Output()
  • 现在只是使用 HBox()VBox()
  • 创建 UI 的例子
  • 现在已经演示了如何通过打印到 stdout 来导出。这显然可以将 JSON 保存到文件
# Import libraries
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import json
import ipywidgets as widgets

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

fig=go.FigureWidget([go.Scatter(x=x, y=y, mode='markers'), go.Scatter(x=[], y=[], mode="lines")])

fig.update_layout(template='simple_white')

scatter=fig.data[0]
line = fig.data[1]
colors=['#a3a7e4']*100
scatter.marker.color=colors
scatter.marker.size=[10]*100
fig.layout.hovermode='closest'

fig.update_traces(marker=dict(line=dict(color='DarkSlateGrey')))

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

# create our callback function
@out.capture()
def update_point(trace, points, selector):
    x = list(line.x) + points.xs
    y = list(line.y) + points.ys
    line.update(x=x, y=y)
scatter.on_click(update_point)

reset = widgets.Button(description="Reset")
export = widgets.Button(description="Export")

@out.capture()
def on_reset_clicked(b):
    line.update(x=[], y=[])
    out.clear_output()
@out.capture()
def on_export_clicked(b):
    print(fig.to_dict()["data"][1])

reset.on_click(on_reset_clicked)
export.on_click(on_export_clicked)

widgets.VBox([widgets.HBox([reset, export]), widgets.VBox([fig, out])])