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

问题描述 投票:0回答:2

我正在学习在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")]

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

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

这可能吗?

python bokeh
2个回答
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")]

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

© www.soinside.com 2019 - 2024. All rights reserved.