繁体   English   中英

Bokeh,如何使用 CustomJS 回调更改用于字形 colors 的列?

[英]Bokeh, how to change column used for glyph colors with CustomJS callbacks?

我正在使用 Bokeh 通过将ColumnDataSource传递给figure.circle function 来创建散点图。数据源具有为每个点指定特定 colors 的列,每行都有一个十六进制代码,因为我想使用的着色方案是有点复杂。

有没有办法更改用于在小部件回调中为圆圈着色的列? 我在想象一个下拉菜单,允许用户为点选择各种着色方案。

下面是使用models.CustomJS的解决方案示例。选择widget和models.Select从图Figure.circleColumnDataSource中定义的两种着色方案中Figure.circle

import bokeh
import bokeh.plotting
p = bokeh.plotting.figure(x_range=(0,4), y_range=(0,4), plot_height=200 )
csource = bokeh.models.ColumnDataSource(data=dict(
        x=[1,2,3],
        y=[1,2,1],
        colors1=["#ff0000","#00ff00","#0000ff"],
        colors2=["#ff00ff","#ffff00","#00ffff"]))
cir = p.circle(x="x",y="y",fill_color="colors1",line_color="colors1",
               size=20,source=csource)
cb_cselect = bokeh.models.CustomJS(args=dict(cir=cir,csource=csource), code ="""
    var selected_color = cb_obj.value;
    cir.glyph.line_color.field = selected_color;
    cir.glyph.fill_color.field = selected_color;
    csource.trigger("change")
""")
color_select = bokeh.models.Select(title="Select colors", value="colors1", 
                    options = ["colors1","colors2"], callback = cb_cselect)
layout = bokeh.layouts.gridplot([[p],[color_select]])
bokeh.io.output_file("output.html")
bokeh.io.show(layout)

输出看起来像 在此输入图像描述

我更新了Pablo Reyes 为 Bokeh 2.4.1 提供的出色答案

import bokeh
import bokeh.plotting

p = bokeh.plotting.figure(x_range=(0,4), y_range=(0,4), plot_height=200 )
csource = bokeh.models.ColumnDataSource(data=dict(
        x=[1,2,3],
        y=[1,2,1],
        colors1=["#ff0000","#00ff00","#0000ff"],
        colors2=["#ff00ff","#ffff00","#00ffff"]))

cir = p.circle(x="x",y="y",fill_color="colors1",line_color="colors1",
               size=20,source=csource)

cb_cselect = bokeh.models.CustomJS(args=dict(cir=cir,csource=csource), code ="""
    var selected_color = cb_obj.value;
    cir.glyph.line_color.field = selected_color;
    cir.glyph.fill_color.field = selected_color;
    csource.change.emit();
""")

color_select = bokeh.models.Select(title="Select colors", value="colors1", 
                    options = ["colors1","colors2"])

color_select.js_on_change('value', cb_cselect)

layout = bokeh.layouts.gridplot([[p],[color_select]])
bokeh.io.output_file("output.html")
bokeh.io.show(layout)

本质上,JavaScript csource.trigger("change")在 JavaScript 中触发了一个错误:

Uncaught TypeError: csource.trigger is not a function

csource.change.emit()替换它会产生所需的结果。 虽然source.change.emit()没有很好的记录,但这里有一些例子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM