我需要动态地分层(或嵌套)多个Bokeh转换,其中大多数是CustomJSTransforms。反正有这样做吗?
有什么办法可以使用如下语法:Log10Transform(ThresholdTransform(column_name))
要么LinearColorMapper(Log10Tranform(column_name))
我目前正在使用{'field':column_name, 'transform':Log10Transform}
似乎不允许分层的语法。
我可以通过编写大量可怕的变换来处理纯数学变换的分层,但是据我所知,我没有办法做ColorTransform(MathTransform(...))
。
为了防万一,我正在使用Bokeh v 12.5,并且没有升级的能力。
最佳答案
composite_transform()
一一调用transforms
:
from inspect import Signature, Parameter
def composite_transform(*transforms):
def trans_func():
transforms = arguments
res = x
for transform in transforms.values():
res = transform.compute(res)
return res
def vtrans_func():
transforms = arguments
res = window.Array["from"](xs)
for transform in transforms.values():
res = transform.v_compute(res)
return res
parameters = [Parameter("T{:02d}".format(i), Parameter.POSITIONAL_OR_KEYWORD, default=trans)
for i, trans in enumerate(transforms)]
trans_func.__signature__ = Signature(parameters=parameters)
vtrans_func.__signature__ = Signature(parameters=parameters)
trans = CustomJSTransform.from_py_func(trans_func, vtrans_func)
return trans
这是一个例子:
进口:
import numpy as np
from bokeh.io import output_notebook, show
from bokeh.models import ColumnDataSource, ColorBar, CustomJS
from bokeh.models.transforms import CustomJSTransform
from bokeh.transform import transform
from bokeh.models.mappers import LinearColorMapper
from bokeh.palettes import Viridis, Category10
from bokeh.plotting import figure
from bokeh.layouts import row, column
output_notebook()
绘图:
x, y = np.random.normal(scale=0.2, size=(2, 500))
source = ColumnDataSource(data=dict(x=x, y=y))
fig = figure(plot_width=400, plot_height=300)
def dummy(source=source):
return 0
def vtrans_value(source=source):
data = source.data
return [(data.x[i]**2 + data.y[i]**2)**0.5 for i in range(len(data.x))]
def vtrans_size():
return [10 * x for x in window.Array["from"](xs)]
value_transform = CustomJSTransform.from_py_func(dummy, vtrans_value)
mult_transform = CustomJSTransform.from_py_func(dummy, vtrans_size)
cmap_transform = LinearColorMapper(Viridis[256], low=0, high=0.6)
color_transform = composite_transform(value_transform, cmap_transform)
size_transform = composite_transform(value_transform, mult_transform)
c = fig.circle("x", "y",
fill_color=transform("x", color_transform),
size=transform("x", size_transform),
line_color=None, source=source, alpha=1)
colorbar = ColorBar(color_mapper=cmap_transform, label_standoff=12, border_line_color=None, location=(0,0))
fig.add_layout(colorbar, "right")
show(fig)
结果:
关于python - 分层(或嵌套)多个散景变换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48772907/