添加悬停工具提示到散景直方图

时间:2015-03-05 16:15:22

标签: python hover tooltip bokeh

我使用以下代码在散景中创建了直方图:

TOOLS="pan,wheel_zoom,box_zoom,reset,hover"

for column in valid_columns:
    output_file_name = str( file_name + column + ".html" )
    data_values = stats[ column ].tolist()

    output_file( output_file_name )
    histogram, edges = np.histogram( data_values, bins=50 )

    source = ColumnDataSource(
        data = dict( data_value = data_values ) )

    p1 = figure( title = column, background_fill="#E8DDCB", tools=TOOLS )
    p1.quad( top = histogram, bottom = 0, left = edges[ :-1 ], right = edges[ 1: ], 
             fill_color = "#036564", line_color = "#033649" ) 

    hover = p1.select(dict(type=HoverTool))
    hover.tooltips = [ ( "Value", "@data_value" ) ]

    show( p1 )
    print( "Saved Figure to ", output_file_name )   

其中有效列是我想在 pandas 数据框中检查的所有列的列表。我正在尝试添加一个悬停工具提示,它将显示存储在每个bin中的项目数,但我无法这样做。任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果您不想使用CDS,则可以将@data_value替换为@top,并且它只需进行最少的编辑即可工作:

hover = HoverTool(tooltips = [('Value', '@top')])
p.add_tools(hover)

即以这种方式编辑示例histogram.py也可以:

from bokeh.models import HoverTool

def make_plot(title, hist, edges, x, pdf, cdf):
    p = figure(title=title, tools='', background_fill_color="#fafafa")
    p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
       fill_color="navy", line_color="white", alpha=0.5)
    p.line(x, pdf, line_color="#ff8888", line_width=4, alpha=0.7, legend_label="PDF")
    p.line(x, cdf, line_color="orange", line_width=2, alpha=0.7, legend_label="CDF")

    p.y_range.start = 0
    p.legend.location = "center_right"
    p.legend.background_fill_color = "#fefefe"
    p.xaxis.axis_label = 'x'
    p.yaxis.axis_label = 'Pr(x)'
    p.grid.grid_line_color="white"
    hover = HoverTool(tooltips = [('Density', '@top')])
    p.add_tools(hover)
    return p

答案 1 :(得分:1)

看起来你错过了几件事:

  1. source长度与histogram相同,而不是data_values。更具体一点,我想你希望source成为:

    source = ColumnDataSource( data = dict( data_value = histogram ) )
    
  2. source添加到p1.quad来电,即

    p1.quad( top = histogram, bottom = 0, left = edges[ :-1 ], right = edges[ 1: ], 
             fill_color = "#036564", line_color = "#033649", source = source )