如何通过在散景中使用选择小部件设置源来更新绘图

时间:2017-10-19 13:43:19

标签: python pandas visualization bokeh

我有2个pandas数据帧,列名相同。我尝试根据散景选择小部件更新我的情节。

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运行此操作当我使用Select小部件时出现以下错误:

错误处理消息消息'PATCH-DOC'(修订版1):ValueError('期望ColumnData的一个元素(String,Seq(Any)),得到时间y \ n0 1 2 \ n1 2 1 \ n2 3 1 \ n3 4 8',)

你能帮帮我吗?

2 个答案:

答案 0 :(得分:2)

关注this example,您需要将source.data设置为dict,而不是DataFrame。因此,您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 

答案 1 :(得分:0)

如果您正在使用联接的数据帧并处理结果,那么不引用原始源元素(如dict)会更容易:

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