您的位置:宽带测速网 > 编程知识 > 如何在Bokeh中实现图表的动态选择和过滤器

如何在Bokeh中实现图表的动态选择和过滤器

2025-06-27 17:08来源:互联网 [ ]

要在Bokeh中实现图表的动态选择和过滤器,可以使用Bokeh的widgets和回调函数来实现。以下是一个简单的示例:

    首先,创建一个数据源和一个图表:
from bokeh.plotting import figure, show, output_filefrom bokeh.models import ColumnDataSourceimport pandas as pddata = {'x': [1, 2, 3, 4, 5],'y': [6, 7, 2, 4, 5],'color': ['red', 'blue', 'green', 'yellow', 'orange']}df = pd.DataFrame(data)source = ColumnDataSource(df)p = figure()p.circle('x', 'y', color='color', source=source)
    创建一个选择器和一个过滤器:
from bokeh.models import Selectselect = Select(title='Color', options=['All'] + df['color'].unique().tolist(), value='All')def update_plot(attrname, old, new):if select.value == 'All':new_data = dfelse:new_data = df[df['color'] == select.value]source.data = ColumnDataSource.from_df(new_data)select.on_change('value', update_plot)
    最后,显示图表和选择器:
from bokeh.layouts import columnoutput_file('filter.html')layout = column(select, p)show(layout)

现在,您可以在选择器中选择颜色,并动态过滤图表中显示的数据。