Python 散景 - 使用选择小部件和交互式图例的交互式绘图 - 空的 html 文件



我在与散景密谋时遇到了一些问题。"类别"有一个过滤器,因此绘图应该在变化时更新。此外,情节还有一个互动图例。

代码一定有什么问题。我在 jupyter 笔记本中收到错误"BAD-COLUMN_NAME",但可能也存在问题,并且 html 文件为空。拜托,我在这里需要一些帮助。谢谢!

# Perform necessary imports
import pandas as pd
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.models import CustomJS, HoverTool, ColumnDataSource, Select
from bokeh.palettes import Category20_20
from bokeh.layouts import layout, widgetbox, gridplot
#Dataframe
df = pd.DataFrame({'Reg': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
'Category': ['Cat1', 'Cat1', 'Cat1', 'Cat2', 'Cat2', 'Cat2', 'Cat3', 'Cat3', 'Cat3', 'Cat3'],
'X': ['751', '673', '542', '762', '624', '536', '845', '626', '876', '233'],
'Y': ['458', '316', '287', '303', '297', '564', '278', '834', '234', '623'],
'Size': ['5', '9', '5', '8', '10', '22', '23', '12', '9', '20'],           
'User': ['u1', 'u2', 'u3', 'u1', 'u2', 'u3', 'u1', 'u2', 'u3', 'u3']           
})
# Make the ColumnDataSource
source = ColumnDataSource(data=dict(Reg=df['Reg'], Category=df['Category'], x=df['X'], y=df['Y'], Size=df['Size'], User=df['User']))
filteredSource = ColumnDataSource(data=dict(Reg=[], Category=[], x=[], y=[], Size=[], User=[]))
#Create widget
category = list(set(df['Category']))
category.sort()
category_select = Select(title="Category:", value=category[0], options=category)
#Callback
callback = CustomJS(args=dict(source=source, filteredSource=filteredSource, 
category_select=category_select), code="""
const data = source.data;
var f = cb_obj.value;
const df2 = filteredSource.data;
df2['category']=[]
for(i = 0; i < data['category'].length;i++){
if(data['category'][i]==f){
df2['category'].push(data['category'][i])
}
}
filteredSource.change.emit()
""")
category_select.js_on_change('value', callback)
# Create the figure: p1
p1 = figure(x_axis_label='x)', y_axis_label='y', 
plot_width=450, plot_height=450, tools=['box_select', HoverTool(tooltips='Size: @size')])
# Add a circle glyph to p1
users=list(set(df['User']))
for name, color in zip(users, Category20_20):
user_df = df[df['User'] == name]
p1.circle(x='X', y='Y', size='Size',
color=color, alpha=0.8, source=filteredSource, legend=name)
p1.legend.location = "top_right"
p1.legend.click_policy="hide"
#layout
layout = gridplot([widgetbox(category_select), p1], ncols=2, sizing_mode='scale_both')
show(layout)

列名中的字符大小写不一致。您使用例如xX.您必须坚持使用一个变体并在任何地方使用它 - 在数据源中、创建字形呈现器时的列规范中、在CustomJS代码中等。

此外,您的CustomJS代码是错误的。i = 0将导致错误 - 您应该改用let i = 0。而且,您还只更新Category列,而您必须更新所有列以确保它们的长度相同。

作为旁注,从这个问题和其他问题来看,您可能会发现本文档部分非常有用:https://docs.bokeh.org/en/latest/docs/user_guide/data.html#filtering-data。此处描述的方法有助于防止编写 JS 代码和未加密的数据搅动。这里和Bokeh的话语中有很多例子。

最新更新