在ColumnDataSource的颜色和mapper的颜色之间进行bokeh切换

时间:2019-02-28 18:48:51

标签: bokeh

我想在字形的颜色之间进行切换,并在ColumnDataSource中保存的颜色和映射器定义的颜色之间进行回调。当我设法从ColumnDataSource切换到映射器时,我无法使它以其他方式起作用。

这里是一个例子:

import numpy as np
from bokeh.models import ColumnDataSource, CustomJS, Select
from bokeh.transform import linear_cmap
from bokeh.palettes import Spectral6
from bokeh.plotting import figure, show
from bokeh.layouts import column, row


x=[1,2,3]
y=[1,2,3]
colormap=[5,6,7]
category=[1,1,2]
color=np.full((len(x)),'green')
legend=np.full((len(x)),'all data')

source = ColumnDataSource(data={'x':x, 'y':y , 'colormap': colormap, 'category': category,'color':color, 'legend':legend})
mapper = linear_cmap(field_name='colormap', palette=Spectral6, low=colormap[0], high=colormap[2])
p1=figure(plot_width=400, plot_height=400)

r=p1.circle('x','y',source=source, fill_color='color', size=20 ,legend='legend')

callback=CustomJS(args=dict(source=source,r=r,mapper=mapper),code='''
var color=source.data['color']
var category=source.data['category']
var legend=source.data['legend']
var r = r
var mapper = mapper
var n = color.length;
if (cb_obj.value == "no distinction"){
    for (var i = 0; i < n; ++i) {
    color[i] = 'blue';
    legend[i] = 'all data';

    source.change.emit();
    }
    }

else if (cb_obj.value == "category"){
    for (var i = 0; i < n; ++i) {
    if ( category[i] == 1){
    color[i] = 'red';
    legend[i] = 'category 1';

    source.change.emit();
    }
    else if (category[i] == 2 ){
    color[i] = 'black';
    legend[i] = 'category 2';
    source.change.emit();

    }
    }
    }
else if (cb_obj.value == "mapper"){
    r.glyph.fill_color = mapper
    r.change.emit();

    }
'''
)

select = Select(title=None, value="foo", options=["no distinction", "mapper", "category"])
select.js_on_change('value', callback)

show(column(select,p1))

如果选择第一个类别,然后选择映射器。该代码执行应做的事情。但是,当再次选择类别时,左侧图将不再更改其值。 我猜解决方案是在回调的开头将ColumnDataSource分配给字形,例如:

r.glyph.fill_color = color

但是,我不知道如何将ColumnDataSource对象分配给字形。

1 个答案:

答案 0 :(得分:0)

r.glyph.fill_color = {field : 'color'}