File size: 2,243 Bytes
89c908a
7f871a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89c908a
7f871a7
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
### Scatter Plot with Slider

# this is demo is based on the topic discussed on stackoverflow
# https://stackoverflow.com/questions/78542719/streamlit-slider-will-refresh-the-whole-page-and-go-to-the-top

import simplestart as ss
from bokeh.plotting import figure
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.resources import CDN
from bokeh.embed import file_html, components


### ui
ss.md('''
#### This example uses a slider outside of Bokeh to change the chart data, combining the smoothness of JavaScript with the convenience of Python.
---
''')

# Title for the application
ss.write('# Bernoulli Distribution Visualization')


def plot(p=0.5):
    x = [0, 1]
    y = [1 - p, p]

    colors = ['#1f77b4', '#ff7f0e']
    source = ColumnDataSource(data=dict(x=x, y=y, color=colors))
    source.name = "mysource"

    fig = figure(
        title="Bernoulli Distribution",
        x_axis_label="Outcome",
        y_axis_label="Probability",
    )

    fig.title.align = "center"

    fig.vbar(x="x", top="y", width=0.5, color="color", source=source)

    return file_html(fig, CDN, "Bernoulli Distribution")

ss.htmlview(plot())

def change_value(value):
    js = f'''
        const iframe = document.getElementById('myIframe');

        const innerWindow = iframe.contentWindow;

        const bokehDoc = iframe.contentWindow.Bokeh.documents[0];
        const source = bokehDoc.get_model_by_name("mysource"); 
        //console.log("source", source)

        // updata source data
        var value = {value};
        source.data['y'] = [1 - value, parseFloat(value)];
        source.change.emit();
    '''
    return js


def slider_change(event):
    ss.exec_js(change_value(event.value))
    
ss.slider('Probability of Success \(p\)', 0.0, 1.0, 0.5, onchange=slider_change, triggerOnUpdate = True)


ss.space()
ss.md('''
---
### Related References:
[Streamlit slider will refresh the whole page and go to the top](https://stackoverflow.com/questions/78542719/streamlit-slider-will-refresh-the-whole-page-and-go-to-the-top) (stackoverflow)

[source code of this demo](https://github.com/readever/simplestart/tree/main/demo/stackoverflow/slider%20outside%20of%20bekoh) (github)
''')