如何使用Bokeh中的Select小部件设置数据源来更新绘图

4

我有两个名字相同的pandas数据框。我尝试根据bokeh选择小部件更新我的绘图。

app.py

from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, output_file, show, output_notebook
from bokeh.models.widgets import Select
from bokeh.io import curdoc
from bokeh.layouts import column, row

import pandas as pd

d1 = {'time': [1,2,3,4], 'y': [2,4,6,8]}
d2 = {'time': [1,2,3,4,5], 'y': [2,1,1,8,22]}
df1 = pd.DataFrame(data=d1, )
df2 = pd.DataFrame(data=d2, )

source = ColumnDataSource(df1 )

p = figure()
r = p.vbar(x='time', top='y', width=1,
         source = source)

select = Select(title="monthly csv-s",  options=['d1', 'd2'])

def update_plot(attrname, old, new):
    if select.value == 'd1':
        newSource = df1
    if select.value == 'd2':
        newSource = df2
    source.data =  newSource 


select.on_change('value', update_plot)
layout = column(row(select, width=400), p)
curdoc().add_root(layout)

我尝试使用bokeh serve --show app.py运行此应用程序时,当我使用选择部件时出现以下错误: 处理消息“PATCH-DOC”(修订版1)时出错:ValueError('expected an element of ColumnData(String, Seq(Any)), got time y\n0 1 2\n1 2 1\n2 3 1\n3 4 8') 你能帮我解决这个问题吗?
2个回答

3

参考此示例,您需要将source.data设置为字典而不是数据框。因此,update_plot()的新代码如下:

def update_plot(attrname, old, new):
    if select.value == 'd1':
        newSource = d1  # changed this to the dict
    if select.value == 'd2':
        newSource = d2  # changed this to the dict
    source.data =  newSource 

2
谢谢,我的数据来自一个csv文件。d1和d2只是我举例用的,但是df.to_dict('list')成功解决了我的问题。 - user3598726
我收到了错误信息 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7fc47ea98b70>: Cannot run the event loop while another loop is running File "base_events.py", line 417, in run_forever .. 200 GET /test_bokeh_app (127.0.0.1) 130.17ms,但是应用程序似乎仍在运行。 - InLaw

0

如果你正在使用连接的数据框并对结果进行操作,最好不要引用原始源元素(如字典):

def update_plot(attrname, old, new):
   if select.value == 'd1':
       newSource =  ColumnDataSource(df1) 
   if select.value == 'd2':
       newSource =  ColumnDataSource(df2) 
   source.data = newSource.data

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接