【问题标题】:Removing data from a line graph interactively in Jupiter notebook从 Jupyter notebook 中交互式的折线图中删除数据
【发布时间】:2023-02-06 06:20:47
【问题描述】:

我有一个 NumPy 数组,其中包含来自多个样本的数据。一些样品是异常值,需要通过目视检查去除。有没有办法在 jupyter notebook 中制作交互式线图,用户可以通过单击它在图上选择一条线并使该线消失/突出显示并将数据标记为删除?

到目前为止,我想到的最好的方法是使用 Plotly:

import plotly.graph_objects as go

x = np.linspace(0,100)
y = np.random.randint(5, size=(5, 100))

fig = go.Figure()

for line in range(5):
    fig.add_trace(go.Line(x=x, y=y[:,line],mode='lines'))

f = go.FigureWidget(fig)

f

Plotly output line graph

使用这段代码,我可以得到一个折线图,其中可以通过选择图例中的相应标签来选择线条,但是随着样本的增多,这很快变得不可行。有没有办法在不绘制图例和直接在图表中选择线条的情况下做到这一点?

谢谢

【问题讨论】:

    标签: python plotly jupyter interactive linegraph


    【解决方案1】:

    您可以使用 click events 来定义绑定到每个跟踪的回调。下面是一个回调示例,它会在点击时删除跟踪(@out.capture 装饰器不是必需的,但对于使用 print 语句进行调试很有用):

    import numpy as np
    import plotly.graph_objects as go
    from ipywidgets import Output, VBox
    
    np.random.seed(42)
    x = np.linspace(0,100)
    y = np.random.randint(5, size=(5, 50))
    
    fig = go.Figure()
    
    for line in range(5):
        fig.add_trace(go.Scatter(x=x, y=y[line,:],mode='lines',visible=True,name=f'trace_{line+1}'))
    
    f = go.FigureWidget(fig)
    
    out = Output()
    
    @out.capture(clear_output=False)  
    def update_trace(trace, points, selector):
        
        ## determine whether trace was clicked on
        if points.point_inds == []:
            pass
        else:
            selected_trace_name = trace.name
            for f_trace in f.data:
                if (selected_trace_name == f_trace.name) & (f_trace.visible == True):
                    f_trace.visible = False
                    print(f"removing {selected_trace_name}")
    
    traces = f.data
    for trace in traces:
        trace.on_click(update_trace)
    
    VBox([f, out])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2018-05-11
      • 2018-10-03
      • 1970-01-01
      • 2015-10-21
      • 2018-01-23
      • 2015-04-24
      相关资源
      最近更新 更多