pythonvisual-studio-codeplotjupyter-notebookbokeh

bokeh interactor and push_notebook doesn't refresh in VScode


I found a way to implement interactive slider using Bokeh without relying on Bokeh server, since Bokeh server doesn't work in VS code.

But this new way doesn't work in vs code either, though it still works in web browser.

Is it possible to run it in vs code?


Solution

  • It is possible. It's even possible to make it automatically refresh the graph when interacting with the sliders.

    Steps:

    1. Wrap the graphs with a jupyter_bokeh.widgets.BokehModel
    2. Instead of show, use IPython.display
    3. Remove push notebook

    Fully functional end result:

    from IPython.display import display
    from jupyter_bokeh.widgets import BokehModel
    from bokeh.io import output_notebook
    from bokeh.plotting import figure
    from ipywidgets import interact
    import numpy as np
    
    output_notebook()
    
    x = np.linspace(0, 2*np.pi, 2000)
    y = np.sin(x)
    
    fig = figure(title="simple line example", height=300, width=600, y_range=(-5,5),
               background_fill_color='#efefef')
    r = fig.line(x, y, color="#8888cc", line_width=1.5, alpha=0.8)
    
    def update(f, w=1, A=1, phi=0):
        if   f == "sin": func = np.sin
        elif f == "cos": func = np.cos
        r.data_source.data['y'] = A * func(w * x + phi)
    
    interact(update, f=["sin", "cos"], w=(0,50), A=(1,10), phi=(0, 20, 0.1))
    
    display(BokehModel(fig))