在工具提示上显示一个范围内的值

时间:2019-03-25 16:33:08

标签: python bokeh

我正在学习在Python上使用Bokeh库。我现在所拥有的是:

source = ColumnDataSource(data=dict(x=x, counts=rates))

我的x值是一个元组数组,如下所示:

x = [('A' ,'1'), ('B', '1'), ('C', '1'), ('A', '2'), ('B', '2'), ('C', '2')]

我想要的是在图形中显示一个工具提示,该提示将显示元组的第二个值(1或2,以相对应的值为准)。我创建了这样的工具提示:

TOOLTIPS = [("Rate", "@counts"), ("Value", "@x")]

第一个(Rate)工作正常,并显示了我想要的值,但第二个显示了两个值(A,1),而我只想显示其中一个(1)。作为记录,这就是我创建图形的方式:

p = figure(x_range=FactorRange(*x), sizing_mode='stretch_both', title="Test",toolbar_location=None, tools="", tooltips=TOOLTIPS)

这可能吗?

2 个答案:

答案 0 :(得分:0)

您可以将x数组分成两个单独的数组,以便...

x = [('A' ,'1'), ('B', '1'), ('C', '1'), ('A', '2'), ('B', '2'), ('C', '2')]

...成为...

x_1 = ["A","B","C","A","B","C"]
x_2 = ["1","1","1","2","2","2"]

然后将这些阵列提供给CDS。

然后,您在工具提示中仅引用x_2,就像...

TOOLTIPS = [("Rate", "@counts"), ("Value", "@x_2")]

答案 1 :(得分:0)

您可以像这样使用HoverTool回调(Bokeh v1.0.4):

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, FactorRange, HoverTool, CustomJS

x = [('A' , '1'), ('B', '1'), ('C', '1'), ('A', '2'), ('B', '2'), ('C', '2')]
rates = [1, 2, 3, 4, 5, 6]

source = ColumnDataSource(data = dict(x = x, counts = rates))

TOOLTIPS = [("Rate", "@counts"), ("Value", "@x")]
p = figure(x_range = FactorRange(*x), sizing_mode = 'stretch_both', title = "Test", toolbar_location = None, tools = "")
p.vbar(x = 'x', top = 'counts', width = 0.2, source = source)

code = '''  if (cb_data.index.indices.length > 0) { 
                index = cb_data.index.indices[0];
                x1 = source.data.x[index][1]
                hover.tooltips[1] = ['Value', x1]; 
            } '''
hover = HoverTool()
hover.tooltips = TOOLTIPS
hover.callback = CustomJS(args = dict(source = source, hover = hover), code = code)
p.add_tools(hover)

show(p)

结果:

enter image description here