我有一个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))