epifanio
epifanio

Reputation: 1357

select and update pandas dataframe columns in bokeh plot

I have a pandas dataframe with several columns and a numeric index which looks like:

import pandas as pd
df = pd.DataFrame({'2007':[10,20,30,40], 
                   '2008':[90,60,70,40], 
                   '2009':[30,60,70,10], 
                   '2010':[80,50,30,10]})
df.index = [0, 0.5, 1, 1.5]

I can plot a specific column of this dataset with bokeh, with the following code:

from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.io import output_notebook, show
from bokeh.models.tools import HoverTool
from bokeh.models import Select
from bokeh.layouts import column

from bokeh.resources import INLINE

output_notebook(INLINE) 

ds = ColumnDataSource(df)
p = figure(toolbar_location="above", 
           x_axis_type="linear") 

p.line(source=ds, y='index', x='2007')

hover = HoverTool(tooltips=[("y", 
                             "@index"),
                           ])

p.add_tools(hover)

show(p)

I am now trying to connect a selector to switch between the data frame's columns using a callback:

handler = CustomJS(args=dict(source=ds), code="""
   // code to update data field
""")

select = Select(title="df-column:", options=list(df.columns))
select.js_on_change('value', handler)

layout = column(select, p)
show(layout)

I don't know how to access and update the values on the X-axis (data field).

Of course, this is due to my lack of understanding of JS and the columndatasource model.

Upvotes: 0

Views: 1962

Answers (1)

Eugene Pakhomov
Eugene Pakhomov

Reputation: 10652

Don't change the data, change the pointers to the data:

import pandas as pd

from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models import Select
from bokeh.models.tools import HoverTool
from bokeh.plotting import figure

df = pd.DataFrame({'2007': [10, 20, 30, 40],
                   '2008': [90, 60, 70, 40],
                   '2009': [30, 60, 70, 10],
                   '2010': [80, 50, 30, 10]},
                  index=[0, 0.5, 1, 1.5])
ds = ColumnDataSource(df)
p = figure(toolbar_location="above", x_axis_type="linear")
p.add_tools(HoverTool(tooltips=[("y", "@index")]))

line_renderer = p.line('2007', 'index', source=ds)

handler = CustomJS(args=dict(line_renderer=line_renderer), code="""
   line_renderer.glyph.x = {field: cb_obj.value};
""")

select = Select(title="df-column:", options=list(df.columns))
select.js_on_change('value', handler)

show(column(select, p))

Upvotes: 1

Related Questions