在此example中,它们在单个go.Scatter跟踪程序中绘制所有内容,然后可以使用selection_fn获取所选点的信息。
我想对我的数据集做类似的事情,它由3个簇组成。为了让集群更容易被看到,我对一个类使用了一个跟踪器。因此,我尝试修改示例代码以适应我的数据集,如下所示。
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import set_credentials_file
import plotly.offline as py
import pandas as pd
import numpy as np
from ipywidgets import interactive, HBox, VBox
from sklearn.datasets import make_blobs
X, y = make_blobs(30,random_state=101)
py.init_notebook_mode()
f = go.FigureWidget([go.Scatter(y = X[y==0][:,1], x = X[y==0][:,0], mode = 'markers'),
go.Scatter(y = X[y==1][:,1], x = X[y==1][:,0], mode = 'markers'),
go.Scatter(y = X[y==2][:,1], x = X[y==2][:,0], mode = 'markers')])
scatter = f.data[0]
N = len(X)
# Create a table FigureWidget that updates on selection from points in the scatter plot of f
t = go.FigureWidget([go.Table(
header=dict(values=['x','y','class'],
fill = dict(color='#C2D4FF'),
align = ['left'] * 5),
cells=dict(values=[X[:,0], X[:,1], y],
fill = dict(color='#F5F8FF'),
align = ['left'] * 5))])
def selection_fn(trace,points,selector):
print(points.point_inds)
t.data[0].cells.values = [X[points.point_inds,0], X[points.point_inds,1], y[points.point_inds]]
scatter.on_selection(selection_fn)
# Put everything together
VBox((HBox(),f,t))错误行为1:返回错误信息
当从trace 0中选择两个数据点时,它确实向我返回了2个信息,但它是错误的。


错误行为2:未返回任何信息
从跟踪器1和2中选择数据点时,它甚至不会返回信息


在简短的调试之后,我注意到每个跟踪器和完整数据集的索引不匹配。这段代码只能从跟踪程序0返回索引,但是,当它将索引传递给完整的数据集时,它会给出这些点的错误缓存信息。当从跟踪器1和2中选择点时,它甚至不能返回索引,因此无法提取任何信息。
虽然我理解这个问题,但我不知道如何修改代码,因为我仍然是plotly的新手。
发布于 2018-12-20 15:00:04
在尝试了几天之后,我想出了一个实现它的方法。(也许仍然有人可以提供更好的方法?)
诀窍是为表中的每一列创建3个列表,并将所选点的数据附加到列表中,最后更新表。
下面是完整的代码。
X, y = make_blobs(30,random_state=101)
py.init_notebook_mode()
f = go.FigureWidget([go.Scatter(y = X[y==0][:,1], x = X[y==0][:,0], text=y[y==0], mode = 'markers', name='class 0'),
go.Scatter(y = X[y==1][:,1], x = X[y==1][:,0], text=y[y==1], mode = 'markers', name='class 1'),
go.Scatter(y = X[y==2][:,1], x = X[y==2][:,0], text=y[y==2], mode = 'markers', name='class 2')])
# Create a table FigureWidget that updates on selection from points in the scatter plot of f
t = go.FigureWidget([go.Table(
header=dict(values=['x','y', 'class'],
fill = dict(color='#C2D4FF'),
align = ['left'] * 5),
cells=dict(values=[X[:,0], X[:,1], y],
fill = dict(color='#F5F8FF'),
align = ['left'] * 5))])
# def data_append(trace,points,selector):
# X1 = []
# X2 = []
# c = []
X1 = []
X2 = []
data_cluster = []
num_called = 0
def selection_fn(trace,points,selector):
global num_called
global X1, X2, data_cluster
if num_called == 3: # number of scatters
num_called = 0
X1 = []
X2 = []
data_cluster = []
X1.extend(trace['x'][points.point_inds])
X2.extend(trace['y'][points.point_inds])
data_cluster.extend(trace['text'][points.point_inds])
t.data[0].cells.values = [X1, X2,data_cluster]
num_called +=1
for scatter in f.data:
scatter.on_selection(selection_fn)
# Put everything together
VBox((HBox(),f,t))代码的输出


如您所见,该表准确地返回了三个选定数据点的信息。
https://stackoverflow.com/questions/53827778
复制相似问题