如何通过回调函数将一个Bokeh小部件的输出用作另一小部件的输入?

时间:2019-04-24 13:29:25

标签: python callback widget bokeh

对于某些公司,我有一个带有某些随机特征(因素)的数据框。我想在第一个小部件中选择一个因素,然后在第二个小部件的最小值和最大值进行相应更新。我使用下面的代码尝试了此操作,但是由于我不是JS方面的专家,所以我真的不知道如何处理。非常欢迎您的帮助或提示。

非常感谢您

马修

import math
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource, HoverTool,CustomJS
from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.models.widgets import Slider, Select, TextInput,RangeSlider,DataTable,TableColumn
from bokeh.layouts import layout, column


CompanyList = ['00', '01', '02','03'] 

a = pd.DataFrame({
    'Factor1' : [random.randint(0, 10) for t in range(4)], 
    'Factor2' : [random.randint(0,100) for t in range(4)],
    'Factor3' : [random.randint(0,1000) for t in range(4)],
    'CompanyNo' : CompanyList})

a =a.set_index('CompanyNo')

C1 = Select(title="Constraint No1", options=sorted(list(a.columns)), value='Factor1')
R1 = RangeSlider(title="Range Constraint 2",value=(a[C1.value].min(),a[C1.value].max()),start=a[C1.value].min(),end=a[C1.value].max(),step=0.1,width=300)

这部分我需要帮助:

C1.callback = CustomJS(args=dict(R1=R1,C1=C1,a=a), code="""
    R1.start = a[C1.value].min()                   
    R1.end = a[C1.value].max();
    """)

show(column(C1,R1))

1 个答案:

答案 0 :(得分:1)

由于DataFrame不可序列化,因此必须以列表格式分别传递其列。我在Bokeh v1.1.0中测试了代码。

import math
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource, HoverTool, CustomJS
from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.models.widgets import Slider, Select, TextInput, RangeSlider, DataTable, TableColumn
from bokeh.layouts import layout, column

CompanyList = ['00', '01', '02', '03']

a = pd.DataFrame({
    'Factor1' : [random.randint(0, 10) for t in range(4)],
    'Factor2' : [random.randint(0, 100) for t in range(4)],
    'Factor3' : [random.randint(0, 1000) for t in range(4)],
    'CompanyNo' : CompanyList})

a = a.set_index('CompanyNo')

C1 = Select(title = "Constraint 1", options = sorted(list(a.columns)), value = 'Factor1')
R1 = RangeSlider(title = "Range Constraint 2", value = (a[C1.value].min(), a[C1.value].max()), start = a[C1.value].min(), end = a[C1.value].max(), step = 0.1, width = 300)

C1.callback = CustomJS(args = dict(R1 = R1, C1 = C1, Factor1 = a['Factor1'].values, Factor2 = a['Factor2'].values, Factor3 = a['Factor3'].values), code = """
    array = eval(C1.value)
    R1.start = Math.min(...array);                  
    R1.end = Math.max(...array);
    R1.value = [Math.min(...array), Math.max(...array)];    
    """)

show(column(C1, R1))