Search code examples
bokeh

How to display plot in Bokeh Div?


Here's my plot:

from bokeh.plotting import figure

plot = figure()
plot.circle([1,2], [3,4])

Here's my div:

myDiv = Div(text="<b>I want my plot to go in here!</b>", style={'color': 'blue'})

I want to be able to run the following code to see my plot:

show(myDiv)

How do I get a plot into my div?


Solution

  • Like I wrote in the comments I suggest using Tabs Another option is to build a Bokeh server app that will remove / add a plot dynamically in the layout.

    Run the code below in Terminal (Bokeh v1.1.0) using bokeh serve --show app.py:

    from bokeh.models import ColumnDataSource, Column, Select
    from bokeh.plotting import curdoc, figure, Figure
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(np.random.randn(5, 2), columns = ['plot1', 'plot2'])
    source = ColumnDataSource(df)
    
    def callback(attr, old, new):
        if new == "plot1":
            layout.children.remove(p2)
            layout.children.append(p1)
    
        if new == "plot2":
            layout.children.remove(p1)
            layout.children.append(p2)
    
    select = Select(value = "plot1", options = ["plot1", "plot2"])
    select.on_change('value', callback)
    
    layout = Column()
    layout.children.append(select)
    
    p1 = figure(title = 'plot1')
    p1.line(source = source, x = 'index', y = 'plot1')
    p2 = figure(title = 'plot2')
    p2.line(source = source, x = 'index', y = 'plot2')
    
    layout.children.append(p1)
    
    curdoc().add_root(layout)
    

    enter image description here