首页 > 解决方案 > 散景 - 如何使用 JS 回调更改 varea_stack 的填充颜色

问题描述

我想在 jupyter 笔记本中绘制一堆像 matplotlib stackplot 这样的线。然后,我想将除一个之外的所有数据灰显,使用选择小部件选择我想要保留的数据。为此,需要回调。

我在更新 Bokeh varea_stack 返回的 VArea 字形渲染器的 fill_color 时遇到问题。

MWE

from bokeh.io import output_notebook, show
from bokeh.layouts import column, 
from bokeh.models import CustomJS, ColumnDataSource, Select
from bokeh.plotting import figure
from bokeh.colors import Color, RGB
output_notebook()

import numpy as np

x = np.arange(0,20)
y1 = 10*np.ones_like(x)
y2 = x

indeces = [1,2]

p = figure()

source = ColumnDataSource(data=dict(x=x,y1=y1,y2=y2))

colors = [RGB(200,50,50), RGB(100,100,250)]

stack = p.varea_stack(["y"+str(i) for i in indeces], x='x', source=source, fill_color=colors)
select = Select(title="Line", value="All", options=["All"]+[str(i) for i in indeces])

args = dict(
    colors = colors,
    stack = stack
)

callback = CustomJS(args=args, code="""
    var k = cb_obj.value
    var colors = colors;
    
    for (var i=0; i<colors.length; i++){
        if (k != "All"){
            if (k != i+1){
            stack[i].fill_color = "rgb(0,0,0)"
            }
            else{
                stack[i].fill_color = colors[i];
            }
        }
        else{
            stack[i].fill_color = colors[i];
        }
    }
""")

select.js_on_change("value", callback)
c = column(select, p)
show(c)

输出

在此处输入图像描述

现在,我想点击 Select Widget 中的“1”,将 y2 对应的数据(即蓝色三角形)变灰。

知道怎么做吗?

标签: callbackjupyterbokeh

解决方案


我找到了答案,我不得不更换

stack[i].fill_color通过stack[i].glyph.fill_color在 js 回调中。


推荐阅读