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

问题描述 投票:0回答:1

我有一些数据框,其中包含一些公司的随机特征(因素)。我想在第一个小部件中选择一个因子,然后相应地更新第二个小部件的最小值和最大值。我尝试使用下面的代码,但由于我不是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)

I need help for this part:

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))
python callback widget bokeh
1个回答
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))
© www.soinside.com 2019 - 2024. All rights reserved.