Search code examples
serverbokeh

Bokeh server plot does not update


LS, All the answers about the same topic did not help me solve my update problem. I think it has to do with the dfs = df.sort_values(by=['E']). I use all the latest versions of the libraries. The examples on the bokeh website work fine on my configuration. Via an update button I want to allow the user to select the prefered sort order. The two other sort buttons will be added when this part works. Here is my code:

import pandas as pd
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource
from bokeh.layouts import gridplot
from bokeh.models import Button

df = pd.DataFrame(dict(A=["AMS", "LHR", "FRA", "PTY", "CGD"], S=[7,-5,-3,3,2], E=[8,3,-2,5,8], C=[5,2,7,-3,-4]))

source = ColumnDataSource(df)

options = dict(plot_width=300, plot_height=200,
               tools="pan,wheel_zoom,box_zoom,box_select,lasso_select")

button = Button(label="Change Sort to E")

p1 = figure(y_range=source.data['A'].tolist(), title="S", **options)
p1.hbar(y='A', right="S", height=0.2, source=source)


p2 = figure(y_range=source.data['A'].tolist(), title="E", **options)
p2.hbar(y="A", right="E", height=0.2, source=source)


p3 = figure(y_range=source.data['A'].tolist(), title="C", **options)
p3.hbar(y="A", right="C", height=0.2, source=source)


def update():
    dfs = df.sort_values(by=['E'])
    source.data = ColumnDataSource.from_df(dfs)


button.on_click(update)

p = gridplot([[button], [p1, p2, p3]], toolbar_location="right")

curdoc().add_root(p)

I run the server via: bokeh serve --show app.py --port 5009

Thank you very much for making the update work.


Solution

  • If you want to change the order of things on a categorical axis, you have to update the range. The order of the factors on the axis is specified exactly by the order of factors you configure for the range, so you will need to re-order the factors to match the sort order you want. So, something like:

    p1.y_range.factors = new_sorted_factors
    

    See

    https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#sorted

    for a complete (standalone) example.