Plotly Figure Widget 帮助我创建一个交互式散点图,即,我可以在散点图上选择数据点,并根据选择我的表小部件显示记录。我需要帮助将此表转换为熊猫数据框。import plotly.graph_objs as goimport plotly.offline as pyimport pandas as pdimport numpy as npfrom ipywidgets import interactive, HBox, VBoxpy.init_notebook_mode()df = pd.read_csv('https://raw.githubusercontent.com/jonmmease/plotly_ipywidget_notebooks/master/notebooks/data/cars/cars.csv')f = go.FigureWidget([go.Scatter(y = df['City mpg'], x = df['City mpg'], mode = 'markers')])scatter = f.data[0]N = len(df)scatter.x = scatter.x + np.random.rand(N)/10 *(df['City mpg'].max() - df['City mpg'].min())scatter.y = scatter.y + np.random.rand(N)/10 *(df['City mpg'].max() - df['City mpg'].min())scatter.marker.opacity = 0.5def update_axes(xaxis, yaxis): scatter = f.data[0] scatter.x = df[xaxis] scatter.y = df[yaxis] with f.batch_update(): f.layout.xaxis.title = xaxis f.layout.yaxis.title = yaxis scatter.x = scatter.x + np.random.rand(N)/10 *(df[xaxis].max() - df[xaxis].min()) scatter.y = scatter.y + np.random.rand(N)/10 *(df[yaxis].max() - df[yaxis].min())axis_dropdowns = interactive(update_axes, yaxis = df.select_dtypes('int64').columns, xaxis = df.select_dtypes('int64').columns)# Create a table FigureWidget that updates on selection from points in the scatter plot of ft = go.FigureWidget([go.Table( header=dict(values=['ID','Classification','Driveline','Hybrid'], fill = dict(color='#C2D4FF'), align = ['left'] * 5), cells=dict(values=[df[col] for col in ['ID','Classification','Driveline','Hybrid']], fill = dict(color='#F5F8FF'), align = ['left'] * 5))])def selection_fn(trace,points,selector): t.data[0].cells.values = [df.loc[points.point_inds][col] for col in ['ID','Classification','Driveline','Hybrid']]scatter.on_selection(selection_fn)# Put everything togetherVBox((HBox(axis_dropdowns.children),f,t))只是期望在将散点图上的点选择到熊猫数据框后创建的表。
3 回答
慕田峪7331174
TA贡献1828条经验 获得超13个赞
可能不是解决它的最优雅的方法,但在你选择你的点之后,你可以输入:
d = t.to_dict() df = pd.DataFrame(d['data'][0]['cells']['values'], index =d['data'][0]['header']['values']).T
t 是类型plotly.graph_objs._figurewidget.FigureWidget
我使用 jupyter notebook,所以我在代码下方的一个单元格中编写了这些代码行,我得到了一个包含所选事件的新 df
开心每一天1111
TA贡献1836条经验 获得超13个赞
假设以下代码突出显示您关心的点:
def selection_fn(trace,points,selector): t.data[0].cells.values = [df.loc[points.point_inds][col] for col in ['ID','Classification','Driveline','Hybrid']]
更改它以返回数据框:
def selection_fn(trace,points,selector): return pd.df([df.loc[points.point_inds][col] for col in ['ID','Classification','Driveline','Hybrid'] if col in {selection}])
列表推导需要更改为仅循环您要返回的点。文档中的示例列表理解:
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
哔哔one
TA贡献1854条经验 获得超8个赞
更好的解决方案:
def selection_fn(trace, points, selector):
t.data[0].cells.values = [
df.loc[points.point_inds][col]
for col in ["ID", "Classification", "Driveline", "Hybrid"]]
selection_fn.df1 = df.loc[points.point_inds]
print(selection_fn.df1)
添加回答
举报
0/150
提交
取消