从 Plotly 散点图上选择的数据点创建 Pandas DataFrame

Plotly Figure Widget 帮助我创建一个交互式散点图,即,我可以在散点图上选择数据点,并根据选择我的表小部件显示记录。我需要帮助将此表转换为熊猫数据框。


import plotly.graph_objs as go

import plotly.offline as py


import pandas as pd

import numpy as np

from ipywidgets import interactive, HBox, VBox


py.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.5


def 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 f

t = 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 together

VBox((HBox(axis_dropdowns.children),f,t))


只是期望在将散点图上的点选择到熊猫数据框后创建的表。

http://img1.mukewang.com/629f300400013c1a12971253.jpg

幕布斯7119047
浏览 344回答 3
3回答

慕田峪7331174

可能不是解决它的最优雅的方法,但在你选择你的点之后,你可以输入:d = t.to_dict() df = pd.DataFrame(d['data'][0]['cells']['values'], index =d['data'][0]['header']['values']).Tt 是类型plotly.graph_objs._figurewidget.FigureWidget我使用 jupyter notebook,所以我在代码下方的一个单元格中编写了这些代码行,我得到了一个包含所选事件的新 df

开心每一天1111

假设以下代码突出显示您关心的点: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

更好的解决方案:    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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python