我正在尝试制作散景散点图(使用来自pandas.DataFrame
的数据),其中x
和y
的轴可由用户更改。至关重要的是,这需要在Jupyter笔记本中工作。
我设法使某些东西正常工作,但是bokeh API对我来说还是很新的。下面的示例仅使用sklearn数据集,并遵循this post的指导。
import pandas as pd
import numpy as np
from bokeh.io import show, output_notebook
from bokeh.layouts import widgetbox,row
from bokeh.models import ColumnDataSource, CustomJS, DataRange1d
from bokeh.plotting import figure
from bokeh.models import LinearColorMapper
from bokeh.palettes import RdYlBu11 as palette
from bokeh.models.widgets import Select
from sklearn.datasets import load_boston
output_notebook()
boston = load_boston()
df = pd.DataFrame(data = boston['data'], columns = boston['feature_names'])
df['x'] = df.iloc[:, 0]
df['y'] = df.iloc[:, 1]
p = figure()
p.y_range, p.x_range = DataRange1d(range_padding=0.1), DataRange1d(range_padding=0.1)
source = ColumnDataSource(df)
p.scatter('x', 'y', source=source)
cols = df.columns.tolist()
y_select = Select(title="Select y:", value = cols[0], options = cols[:-2])
x_select = Select(title="Select x:", value = cols[0], options = cols[:-2])
y_callback = CustomJS(args={'source':source},code="""
var data = source.data;
data['y'] = data[cb_obj.value];
source.change.emit();
""")
x_callback = CustomJS(args={'source':source},code="""
var data = source.data;
data['x'] = data[cb_obj.value];
source.change.emit();
""")
# Add the callback to the select widget.
y_select.callback = y_callback
x_select.callback = x_callback
show(row(p, y_select, x_select))
CustomJS
回调函数?还是有更好的方法来实现上述目标?p.y_range
和p.x_range
。如果我定义 x
或y
,则轴仍会按预期更新。为什么会发生这种情况?x
或y
轴?