温馨提示×

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

小樊
82
2024-05-20 11:36:24
栏目: 编程语言

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

  1. 首先,创建一个数据源和一个图表:
from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource
import pandas as pd

data = {
    '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)
  1. 创建一个选择器和一个过滤器:
from bokeh.models import Select

select = Select(title='Color', options=['All'] + df['color'].unique().tolist(), value='All')

def update_plot(attrname, old, new):
    if select.value == 'All':
        new_data = df
    else:
        new_data = df[df['color'] == select.value]
    source.data = ColumnDataSource.from_df(new_data)

select.on_change('value', update_plot)
  1. 最后,显示图表和选择器:
from bokeh.layouts import column
output_file('filter.html')
layout = column(select, p)
show(layout)

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

0