簡體   English   中英

Python 帶有點擊事件的交互式繪圖

[英]Python interactive plotting with click events

我目前正在嘗試通過 np 引入一些數據,對初始數據 plot 進行一些處理,然后與我的 plot 進行交互。 Plotly 有一個關於如何獲取 plot 並更改數據點顏色的教程(在 jupyter 中使用點擊事件https/python/click-event.com 我希望做的是能夠在 2 個點上單擊單擊事件,然后在所選點之間創建一條線並收集我的線位置。 我在 plotly 中發現的唯一一件事就是將鼠標懸停在數據上,但無法進行此處理。 有沒有比使用 plotly 更好的方法呢? plotly 上的文檔建議只使用破折號,但我還沒有找到使用破折號的方法。 后續問題是,如果我導出 plot ( 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])])

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM