散景选择小部件不更新情节

时间:2018-05-30 11:05:55

标签: python plot bokeh interactive

我一直在stackoverflow上关注一些例子来更新我的情节,并选择'小部件。当我通过anaconda shell运行.py文件时,我会看到情节并选择'小部件。不知何故,我的情节不会更新情节。我必须说数据集有大约11000行(我不知道这是否相关)。我看到一个话题,将数据框转换为字典帮助某人使交互工作。所以我用以下代码做到了:

>>> kwarg = {'name': 'John'}
>>> kwarg['name']
'John'
>>> kwarg['age']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age'
>>>
>>> kwarg.get('age', 25)
25

现在我已经制作了词典,我使用以下代码制作了剧情:

from bokeh.layouts import row, column, widgetbox
from bokeh.plotting import figure, show, output_file, ColumnDataSource
from bokeh.models.widgets import Select
from bokeh.io import curdoc, show

df = pd.read_excel('data.xlsx')

d1 = df.to_dict()
d2 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'compliment'].to_dict()
d3 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'complaint'].to_dict()
d4 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'infrastructure'].to_dict()
d5 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'autority'].to_dict()
d6 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'finance'].to_dict()
d7 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'english'].to_dict()
d8 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'danger'].to_dict()
d9 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'health'].to_dict()
d10 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'sport'].to_dict()
d11 = df[['Polarity', 'Subjectivity']].loc[df['Subject'] == 'remaining'].to_dict()

经过多次不同尝试后,我仍然无法完成互动。我做错了什么?

1 个答案:

答案 0 :(得分:1)

由于您还没有提供数据,我使用此代码创建了虚拟数据 -

import pandas as pd
import random

list_type = ['All', 'Compliment', 'Sport', 'Remaining', 'Finance', 'Infrastructure', 'Complaint', 'Authority',
 'Danger', 'Health', 'English']



df = pd.concat([pd.DataFrame({'Subject' : [list_type[i] for t in range(110)], 
                   'Polarity' : [random.random() for t in range(110)],
                   'Subjectivity' : [random.random() for t in range(110)]}) for i in range(len(list_type))], axis=0)

您需要使用与图表关联的数据源。您可以使用简单的函数来操作数据框,创建columndatasource并更改图表后面的数据 -

options = []
options.append('All')

options.extend(df['Subject'].unique().tolist())
source = ColumnDataSource(df)

p = figure()
r = p.circle(x='Polarity', y='Subjectivity', source = source)

select = Select(title="Subject",  options=options, value="All")
output_notebook()

def update_plot(attr, old, new):
    if select.value=="All":
        df_filter = df.copy()
    else:
        df_filter = df[df['Subject']==select.value]
    source1 = ColumnDataSource(df_filter)
    r.data_source.data = source1.data
select.on_change('value', update_plot)
layout = column(row(select, width=400), p)
#show(layout)
curdoc().add_root(layout)