更新Bokeh中的图表时出现问题

时间:2018-02-07 10:55:44

标签: pandas bokeh

所以我再次与Bokeh斗争,而这一次来自callbacks菜单中的Select ......

以下是具有分类数据的工作示例。绘图工作正常,但在尝试更改类别(来自Select对象)时,没有任何反应!我真的不明白我在这里做错了什么......

import pandas as pd
import math
import numpy as np

from bokeh.models import ColumnDataSource, FactorRange, Select
from bokeh.transform import factor_cmap
from bokeh.plotting import figure, show
from bokeh.palettes import Spectral5
from bokeh.layouts import layout, widgetbox

import random

""" Coloring based on universe """
index_cmap = factor_cmap('x', palette=Spectral5, factors=['Universe_1', 'Universe_2'], start=1)

universe_list = []
category_list_1 = []
category_list_2 = []
category_dependence = {'a' : ['A', 'B', 'C', 'D'], 'b' : ['E', 'F', 'G', 'H'], 'c' : ['I', 'J', 'K', 'L']}

N = 20

for x in range(N):
    universe_list.append(random.choice(['Universe_1', 'Universe_2']))
    category_list_1.append(random.choice(['a', 'b', 'c']))
    # Category 2 is dependent on Category 1
    category_list_2.append(random.choice(category_dependence[category_list_1[-1]]))

data = pd.DataFrame({'X' : category_list_1, 'Y' : category_list_2, 'Z' : np.random.randint(0,N,size=(N, 1)).flatten().tolist(), 'W' : universe_list})
data = data.drop_duplicates(subset=['X','Y','W'])

# Dropdown choices
dropdown_choices = sorted(data['X'].drop_duplicates().tolist())
menu_dropdown = Select(title="Category", options=dropdown_choices, value='a')

def select_category():

    val = menu_dropdown.value 
    selected = data.copy()

    return selected[selected.X.str.contains(val)==True]

def create_plot():

    df_ = select_category()

    x = zip(df_['Y'], df_['W'])
    y = df_['Z'].values
    legend = df_['W'].tolist()

    """ Create new figure... """
    p = figure(x_range=FactorRange(*x), y_range=(0.0, round(y.max()*1.1,0)), plot_height=500, plot_width=800, title='Some fancy title...', toolbar_location=None, tools="hover")
    p.x_range.range_padding = 0.1
    p.xaxis.major_label_orientation = math.pi/3
    p.xaxis.major_label_text_font_size = "0pt"
    p.xgrid.grid_line_color = None

    plot_source = ColumnDataSource(data=dict(x=x, top=y, legend=legend))
    p.vbar(x='x', top='top', width=0.9, source=plot_source, line_color="white", legend='legend', fill_color=index_cmap)

    return p

def update():
    l.children[1] = create_plot()  

controls = [menu_dropdown]
for control in controls:
    control.on_change('value', lambda attr, old, new: update)

inputs = widgetbox(*controls, sizing_mode='fixed')
l = layout([inputs, create_plot()], sizing_mode='fixed') 
show(l)

从上面的代码开始,我想到每次用户对Select对象进行更改时都会创建一个新的图,因为x- / y轴和所有类别都不同 - 而不是仅仅更改plot_source(对或错......)。

非常感谢任何帮助...

1 个答案:

答案 0 :(得分:1)

您实际上并未在lambda中调用update函数。这一行:

control.on_change('value', lambda attr, old, new: update)

应该是这样的:

control.on_change('value', lambda attr, old, new: update())

我将在版本0.12.14(今天发布)中提及它也应该更新现有情节的数据和因素,而不是替换批量图。