select 并更新散景图中的 pandas 数据框列

select and update pandas dataframe columns in bokeh plot

我有一个 pandas 数据框,其中包含多个列和一个数字索引,如下所示:

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]

我可以使用散景绘制此数据集的特定列,代码如下:

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)

我现在正在尝试连接一个选择器以使用回调在数据框的列之间切换:

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)

我不知道如何访问和更新 X 轴(数据字段)上的值。

当然,这是我对JS和columndatasource模型不了解的缘故

不要更改数据,更改指向数据的指针:

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))