python - 使用 Ipywidgets 按索引绘制 DataFrame 的交互式绘图

标签 python pandas seaborn jupyter ipywidgets

我有两个数据框:

import numpy as np
import pandas as pd
import ipywidgets as widgets
import seaborn as sns

df = pd.DataFrame(np.random.rand(6,2), index=['Nr. 1', 'Nr. 2', 'Nr. 3', 'Nr. 4', 'Nr. 5', 'Nr. 6'], columns=['A', 'B', 'C', 'D'])

df2 = pd.DataFrame(np.array([[1, 2, 3, 4]]), columns=['a', 'b', 'c', 'd'])

我想制作一个交互式绘图,我可以通过 df 索引的下拉列表选择 DataFrame 的行。

这是我的方法:

Index= df.index.tolist()
Nr = widgets.Dropdown(options=Nr, value=Nr[0], description='Number:', disabled=False)
button = widgets.Button(description='Plot', disabled = False, button_style='', tooltip = 'Plotting', icon='check')

out = widgets.Output(layout={'border': '1px solid black'})
box = widgets.VBox([Nr, button])
def on_button_clicked(b):
    with out:
         ax = sns.regplot(x=df_2[0], y=df.loc[[Nr]])
button.on_click(on_button_clicked, False)
display(box)

但是,我收到此错误:'None of [Index([Dropdown(description='Nr:', index = 4, options=('Nr. 1', 'Nr. 2', 'Nr .3', 'Nr. 4'), value = 'Nr. 1')], dtype = 'object', name='Nr')] 位于 [index]'

我错过了什么?

最佳答案

import ipywidgets as widgets
from ipywidgets import interact  
import pandas as pd
import numpy as np
import seaborn as sns

# create wide dataframe
df = pd.DataFrame(np.random.rand(6, 4),
                  index=['Nr. 1', 'Nr. 2', 'Nr. 3', 'Nr. 4', 'Nr. 5', 'Nr. 6'],
                  columns=['A', 'B', 'C', 'D'])

# convert the dataframe to long form
df = df.reset_index().melt(id_vars='index')

# convert the categorical value to a number with cat.codes or factorize
df['fac'], cats = df.variable.factorize() 
# df['fac'] = df.variable.astype('category').cat.codes
# cats = df.variable.unique()

# display(df.head())
   index variable     value  fac
0  Nr. 1        A  0.700304    0
1  Nr. 2        A  0.375954    0
2  Nr. 3        A  0.168559    0
3  Nr. 4        A  0.962506    0
4  Nr. 5        A  0.503662    0

交互式情节

# get the unique values from the column used to select the data
idx = df['index'].unique()
@interact(Idx = idx)
def f(Idx):
    # select the relevant data
    data = df[df['index'].eq(Idx)]
    # plot
    ax = sns.regplot(data=data, x='fac', y='value')
    # set the x-ticks and labels
    ax.set_xticks(df.fac.unique(), cats)
    return ax

enter image description here

关于python - 使用 Ipywidgets 按索引绘制 DataFrame 的交互式绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72271574/

相关文章:

python - 导入错误 : No module named 'matplotlib.externals'

python - 如何从时间戳创建每小时/天的seaborn热图,每小时有多个数据点

python - 列名称和绘图中的 Groupby 字符串

python - Pandas 搜索速度/性能/效率

python - 如何将所有列与 Pandas 中的一列进行比较?

python - 在 Pandas 拆分中使用 str

python - 如何使用 Pandas 中的预聚合数据绘制直方图?

python - 无法将像素以正确的形状从 cv 代码传输到 cv2 代码

python - 从 pandas 的列中的值获取特定数量的数据

Python 2.7 和 pip install 与 _markerlib 相关的问题以及安装其他包失败