在 plotly dash 3d scatter 中选择和删除数据点 [英] Select and delete data points in plotly dash 3d scatter

查看:68
本文介绍了在 plotly dash 3d scatter 中选择和删除数据点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将交互性添加到我使用破折号托管的情节 3d 散点图.我的问题包含两个相关部分:

I am trying to add interactivity to a plotly 3d scatter plot which I am hosting using dash. My question contains two related parts:

(i) 我想在我的 3d 散点图中手动选择点并将所选点的颜色更改为红色.选择应该包括点击事件和选择事件.

(i) I would like to manually select points in my 3d scatter and change the selected points' colour to red. Selection should include click event and selection event.

(ii) 我希望能够在按下一个键时从图中删除这些点,例如删除"键.

(ii) I would like to be able to delete these points from the plot on pressing of a key e.g. 'delete' key.

第 (i) 部分类似于情节指南中的示例 https://plot.ly/python/click-events/ 但是,on_click 不能用作 3d 散点图的方法.

Part (i) is similar to an example in the plotly guide https://plot.ly/python/click-events/, however, on_click is not available as a method for 3d scatter charts.

我一直在尝试使用 FigureWidget,因为它显然提供了捕获点击和选择的方法,但 2 天后我正在努力取得进展.

I have been attempting to use FigureWidget as that apparently provides methods to capture clicks and selections, but after 2 days I am struggling to make headway.

示例数据(将下面复制到剪贴板并运行 df = pd.read_clipboard(sep=','))

Example data (copy below to clipboard and run df = pd.read_clipboard(sep=','))

id,x_val,z_val,y_val
a,11.313449728149418,0.13039110880256777,0.5386387766748618
b,11.321463427315383,0.2360697833061771,1.32441455152796
c,10.127132005050942,0.23085014016641864,1.0961116175427044
d,11.639819269465233,0.0958798324712593,0.6506370305953094
e,8.892696370438149,0.08223988244819926,0.6440321391968353
f,6.711586646011124,0.3657515974938044,
g,7.095030650760687,,0.5723062047617504
h,6.4523124528415,,1.293852184258803
i,7.165105300812886,0.4151365420301895,-0.5920674079031845
j,7.480703395137295,0.14284429977557123,1.0600936940126982
k,5.570775744372319,,
l,4.358946555449826,,

我在下面有示例代码,我希望它几乎就在那里(但不完全).这个想法是'handle_click'应该捕获点击事件.我还应该处理选择"事件,尽管我不确定如何执行此操作,因为 3d 散点图不提供选择框或套索工具.通过回调,我什至不确定如何启动,因为没有我可以利用的带有 3d 散点图的 clickData/selectionData 事件(所以 [Input('subindustry-dropdown', 'value')]) 不正确,请注意 subindustry-dropdown 不是我在示例中提供的内容,但我从下拉列表中选择了我的 ID,该下拉列表在我的开发版本中返回一个子行业值.)

I have example code below which I hope is almost there (but not quite). The idea is that 'handle_click' should capture click events. I should also handle 'selection' events, although I am not sure how to do this as 3d scatter plot does not provide a selection box or lassoo tool. With the callback, I'm not even sure how to initiate, as there is no clickData/selectionData event with 3d scatterplot that I can utilize (so [Input('subindustry-dropdown', 'value')]) is incorrect and note that subindustry-dropdown is not something that I have provided in the example, but I select my ids from a dropdown which returns a subindustry value in my development version. )

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

import plotly.graph_objs as go
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.css.append_css({
    "external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"
})

app.layout = html.Div([html.Div(id = '3d-scatter'),
])


# Calculate and store data
@app.callback(Output('3d-scatter', 'children'),
               [Input('subindustry-dropdown', 'value')])
def chart_3d():          
    f = go.FigureWidget(px.scatter_3d(df, x = 'x_val', y = 'y_val', z = 'z_val', hover_name = 'company_nm'))

    f.layout.clickmode = 'event+select'
    f.data[0].on_click(handle_click) # if click, then update point/df.      

    return dcc.Graph(id = '3d_scat', figure=f)

def handle_click(trace, points, selector):
    c = list(f.data[0].marker.color)
    s = list(f.data[0].marker.size)
    for i in points.point_inds:
        c[i] = '#bae2be'
        s[i] = 20
        with f.batch_update():
            f.data[0].marker.color = c
            f.data[0].marker.size = s
    return f.data[0]

推荐答案

这是一个解决方案,它允许:

Here is a solution which allows:

  • 通过单独点击选择点

  • selecting points by clicking individually

按html按钮删除选定的点

delete selected points by pressing html button

按 html 按钮清除选择

clear selection by pressing html button

根据此问题 目前在 3d 图中选择多个点不支持

according to this issue selecting multiple points in a 3d plot is currently not supported

(使用FigureWidget好像没什么区别,所以我去掉了)

(The use of FigureWidget does not seem to make a difference, so I removed it)

import dash
import plotly.express as px
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

import plotly.graph_objs as go
import pandas as pd
import json

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.css.append_css({
    "external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"
})



import pandas as pd
df = pd.DataFrame(columns=['x_val','z_val','y_val'])
df.loc['a'] = [11.313449728149418,0.13039110880256777,0.5386387766748618]
df.loc['b'] = [11.321463427315383,0.2360697833061771,1.32441455152796]
df.loc['c'] = [10.127132005050942,0.23085014016641864,1.0961116175427044]
df.loc['d'] = [11.639819269465233,0.0958798324712593,0.6506370305953094]
df.loc['e'] = [8.892696370438149,0.08223988244819926,0.6440321391968353]
df.loc['f'] = [6.711586646011124,0.3657515974938044,0]
df.loc['g'] = [7.095030650760687,0,0.5723062047617504]
df.loc['h'] = [6.4523124528415,0,1.293852184258803]
df.loc['i'] = [7.165105300812886,0.4151365420301895,-0.5920674079031845]
df.loc['j'] = [7.480703395137295,0.14284429977557123,1.0600936940126982]
df.loc['k'] = [5.570775744372319,0,0]
df.loc['l'] = [4.358946555449826,0,0]

def create_figure(skip_points=[]):
    dfs = df.drop(skip_points)
    return px.scatter_3d(dfs, x = 'x_val', y = 'y_val', z = 'z_val')
f= create_figure()

app.layout = html.Div([html.Button('Delete', id='delete'),
                    html.Button('Clear Selection', id='clear'),
                    dcc.Graph(id = '3d_scat', figure=f),
                    html.Div('selected:'),
                    html.Div(id='selected_points'), #, style={'display': 'none'})),
                    html.Div('deleted:'),
                    html.Div(id='deleted_points') #, style={'display': 'none'}))
])

@app.callback(Output('deleted_points', 'children'),
            [Input('delete', 'n_clicks')],
            [State('selected_points', 'children'),
            State('deleted_points', 'children')])
def delete_points(n_clicks, selected_points, delete_points):
    print('n_clicks:',n_clicks)
    if selected_points:
        selected_points = json.loads(selected_points)
    else:
        selected_points = []

    if delete_points:
        deleted_points = json.loads(delete_points)
    else:
        deleted_points = []
    ns = [p['pointNumber'] for p in selected_points]
    new_indices = [df.index[n] for n in ns if df.index[n] not in deleted_points]
    print('new',new_indices)
    deleted_points.extend(new_indices)
    return json.dumps(deleted_points)



@app.callback(Output('selected_points', 'children'),
            [Input('3d_scat', 'clickData'),
                Input('deleted_points', 'children'),
                Input('clear', 'n_clicks')],
            [State('selected_points', 'children')])
def select_point(clickData, deleted_points, clear_clicked, selected_points):
    ctx = dash.callback_context
    ids = [c['prop_id'] for c in ctx.triggered]

    if selected_points:
        results = json.loads(selected_points)
    else:
        results = []


    if '3d_scat.clickData' in ids:
        if clickData:
            for p in clickData['points']:
                if p not in results:
                    results.append(p)
    if 'deleted_points.children' in ids or  'clear.n_clicks' in ids:
        results = []
    results = json.dumps(results)
    return results

@app.callback(Output('3d_scat', 'figure'),
            [Input('selected_points', 'children'),
            Input('deleted_points', 'children')],
            [State('deleted_points', 'children')])
def chart_3d( selected_points, deleted_points_input, deleted_points_state):
    global f
    deleted_points = json.loads(deleted_points_state) if deleted_points_state else []
    f = create_figure(deleted_points)

    selected_points = json.loads(selected_points) if selected_points else []
    if selected_points:
        f.add_trace(
            go.Scatter3d(
                mode='markers',
                x=[p['x'] for p in selected_points],
                y=[p['y'] for p in selected_points],
                z=[p['z'] for p in selected_points],
                marker=dict(
                    color='red',
                    size=5,
                    line=dict(
                        color='red',
                        width=2
                    )
                ),
                showlegend=False
            )
        )

    return f

if __name__ == '__main__':
    app.run_server(debug=True)

这篇关于在 plotly dash 3d scatter 中选择和删除数据点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆