散景,在不同的矩形上添加悬停工具

时间:2018-03-01 01:36:37

标签: python histogram jupyter bokeh

所以我做了一个双重直方图,比如盈利和亏损。我想将鼠标悬停在蓝色条形图上(利润)并仅显示利润,并显示红色条形图并仅显示损失。 现在,只要我将鼠标悬停在特定类别上,它就会显示盈利和亏损。如果重要的话,在Jupyter中使用output_notebook()

from bokeh.models import ColumnDataSource
y1 = [1,2,3]
y2 = [-1,-2,-3]
x = ['c0','c1','c2']


xr = range(len(x))

source = ColumnDataSource(dict(
    y1 = y1,
    y2 = np.abs(y2),
    xr1 = xr,
    xr2 = np.array(xr) + .5,
    y1adj = np.array(y1)/2,
    y2adj = np.array(y2)/2,
    labels = x
    )
    )


labels = LabelSet(x="xr1", y=0, text='labels', level='glyph',
              x_offset=5, y_offset=-5,  render_mode='canvas',source = source,angle = -pi/2)

hover = HoverTool(tooltips = [('proft','@y1'),('loss','@y2')])


p = figure(tools = [hover])
p.rect(x='xr1',y='y1adj',height='y1',width=.45, source = source,color = 'blue')


p.rect(x='xr2',y='y2adj',height='y2',width=.45, source = source,color = 'red')
p.add_layout(labels)
show(p)

1 个答案:

答案 0 :(得分:0)

我认为您需要使用两个ColumnDataSource

from bokeh.io import show, output_notebook
from bokeh.models import LabelSet, HoverTool
from bokeh.plotting import figure
import numpy as np
from math import pi
output_notebook()

from bokeh.models import ColumnDataSource
y1 = [1,2,3]
y2 = [-1,-2,-3]
x = ['c0','c1','c2']


xr = range(len(x))

source1 = ColumnDataSource(dict(
    y = y1,
    xr1 = xr,
    y1adj = np.array(y1)/2,
    labels = x,
    title = ["proft"] * len(y1),
    color = ["blue"] * len(y1)
    )
)

source2 = ColumnDataSource(dict(
    y = np.abs(y2),
    xr2 = np.array(xr) + .5,
    y2adj = np.array(y2)/2,
    labels = x,
    title = ["loss"] * len(y2),
    color = ["red"] * len(y2)
    )
)


labels = LabelSet(x="xr1", y=0, text='labels', level='glyph',
              x_offset=5, y_offset=-5,  render_mode='canvas',source = source,angle = -pi/2)

hover = HoverTool(tooltips= '<b style="color:@color;">@title</b>: @y',)


p = figure(tools = [hover])
p.rect(x='xr1',y='y1adj',height='y',width=.45, source = source1, color = 'blue')
p.rect(x='xr2',y='y2adj',height='y',width=.45, source = source2, color = 'red')
p.add_layout(labels)
show(p)