Search code examples
pythondata-visualizationbokeh

Python Bokeh: after the button callback function, refreshing my figure


Can you please help me to refresh my figure? I have added new "p" variable within the callback function to reset my figure but it does not work. It just shows me an empty figure. Every time I press the button, it overlaps the new plot on the top of the old one. I have tried to use reset.emit() method but it says 'Figure' object has no attribute 'rest'. I also want to add the title in the figure, but it contains a variable. item_input, but I don't know where to start...

bokeh server version 2.0.2 Python 3.8.1 Tornado 6.0.3

from pandas import read_csv
from pandas import to_datetime

from bokeh.layouts import column
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource, HoverTool, Title, TextInput, Button

source_data = 'somewhere'

def call_back():
    try:
        item_input = item.value

        df = read_csv(source_data)
        df1 = df[df['item'] == int(item_input)]

        title = str(item_input) + ' ' + df1.iloc[0]['name']

        source = ColumnDataSource(data=dict(
            system_qty = df1['system_qty'],
            man_date = to_datetime(df1['man_date']),
        ))

        p.circle(
            x='man_date', y='system_qty'
        )

        hover = HoverTool(
            tooltips = [
                ("Manufacturing Date", "@man_date{%Y-%m-%d}"),
                ("Reserved Qty", "@reserved_qty"),
            ],
            formatters = {
                '@man_date': 'datetime'
            },
        )

        p.add_tools(hover)
        p.add_layout(Title(text="Manufacturing Date", align="center"), "below")
        p.add_layout(Title(text="Quantity", align="center"), "left")

    except ValueError:
        raise

p = figure(x_axis_type='datetime')

item = TextInput(value='', title="Item:")

button = Button(label='Submit')
button.on_click(call_back)

curdoc().add_root(column(item, button, p))


Solution

  • Call methods of p only once, do not call them in a callback. Also, in general you should also create instances of Bokeh models just once, especially of ColumnDataSource. Create it once and then just reassign its data property in the callback.