我正在尝试更新 Bokeh 中的 ColorBar,但是标题和颜色本身都不会更新。这是一个最小的功能示例(Python 3.6.9,Bokeh 2.3.0,Tornado 6.1):
from bokeh.plotting import figure, curdoc
from bokeh.colors import HSL
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, LinearColorMapper, ColorBar, Select
import numpy as np
def colorize(data,reverse=False):
if reverse:
return [HSL(h-180,1.0,0.5).to_rgb() for h in data]
else:
return [HSL(h,1.0,0.5).to_rgb() for h in data]
def update(attr,old,new):
if menu.value == 'reverse':
y = -1 * x
c = colorize(x,reverse=True)
else:
y = 1 * x
c = colorize(x)
source.data = {'x':x,'y':y,'c':c}
#updateColorBar(p.right[0])
updateColorBar(p._property_values['right'][0])
def updateColorBar(cb):
if menu.value == 'reverse':
cb.title = 'reverse'
u = colorize(np.linspace(0,360,101,endpoint=True),
reverse=True)
else:
cb.title = 'normal'
u = colorize(np.linspace(0,360,101,endpoint=True))
newcm = LinearColorMapper(palette=u,low=0.0,high=2*np.pi)
cb.color_mapper.palette = newcm.palette
cb.color_mapper.low = newcm.low
cb.color_mapper.high = newcm.high
# prepare some data
x = np.linspace(0,360,361,endpoint=True)
y = x
c = colorize(x)
source = ColumnDataSource({'x':x,'y':y,'c':c})
# create a new plot with a title and axis labels
p = figure(title="Simple scatter example", x_axis_label="x",
y_axis_label="y",toolbar_location="above")
# create a plot to show the colors
p.scatter('x', 'y',size=2,color='c',source=source)
u = colorize(np.linspace(0,360,101,endpoint=True))
color_mapper = LinearColorMapper(palette=u,low=0.0,high=2*np.pi)
color_bar = ColorBar(color_mapper=color_mapper,
label_standoff=12,
title='normal')
p.add_layout(color_bar, 'right')
menu = Select(title='Order',value='normal',
options=['normal','reverse'])
menu.on_change('value',update)
t = column(children=[menu,p])
# show the results
curdoc().add_root(t)
我正在运行这个示例:
bokeh serve --show file_name.py
。当我从菜单中选择“reverse”时,图形本身会正确更新,但ColorBar未更改。我遵循了这里的建议,尽可能地进行最小更改,但是我的更改可能太小了?我的猜测是LinearColorMapper没有向ColorBar推送更新,但是更改ColorBar的标题也不起作用。
编辑: 通过在更新方法的末尾添加
print(cbar.title)
,我可以看到色条的标题已更新。我从“normal”更改为“reverse”,然后再次从菜单中选择两个项目。似乎ColorBar只是没有被重新绘制。编辑2: 如果尝试完全替换ColorBar,则它会消失。修改更新函数并添加新函数以创建ColorBar:
def update(attr,old,new):
if new == 'reverse':
y = 360 - 1 * x
c = colorize(x,reverse=True)
else:
y = 1 * x
c = colorize(x)
source.data = {'x':x,'y':y,'c':c}
cbar = p.right[0]
#updateColorBar(cbar,new)
p.right[0] = makeColorBar()
print(p.right[0].visible)
def makeColorBar():
if menu.value == 'reverse':
title = 'reverse'
u = colorize(np.linspace(0,360,101,endpoint=True),True)
else:
title = 'normal'
u = colorize(np.linspace(0,360,101,endpoint=True))
cm = LinearColorMapper(palette=u,low=0.0,high=2*np.pi)
return ColorBar(color_mapper=cm,label_standoff=12,
title=title)
当我用另一种方式运行时,使用
python3 -i file_name.py
并询问p.right [0]
的标识符,我得到ColorBar(id ='1042',...)
。如果我手动更改menu.value ='reverse'
(屏幕上打印True),并查看ColorBar的标识符,我会得到ColorBar(id ='1057',...)
。似乎新的颜色条没有被推送到显示器,而旧的颜色条正在被删除。
编辑3:这已经被标记为Bokeh中的错误,计划在版本2.3.2中更新。