给Bokeh直方图添加悬停提示工具

5

我使用以下代码在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个回答

3

如果您不想使用ColumnDataSource,您可以将@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

0

看起来你缺少了一些东西:

有一个与你的直方图(histogram)长度相同的source,不是你的数据值(data_values)。更具体地说,我认为你希望你的source是这样的:
```python source = ColumnDataSource( data = dict( data_value = histogram ) ) ```
把这个source添加到p1.quad的调用中,即:
```python p1.quad( top = histogram, bottom = 0, left = edges[ :-1 ], right = edges[ 1: ], fill_color = "#036564", line_color = "#033649", source = source ) ```

提醒一下,将命名列和自动创建的列(从文字数据值)混合在用户提供的源中将在不久的将来被禁止。 (因为这样做会修改用户提供的源,这可能是意外和不必要的)我建议在源中也放置“top”,“left”和“right”列。 - bigreddot
@bigreddot,您如何将 topleftright 放入源代码中?在直方图库(https://docs.bokeh.org/en/latest/docs/gallery/histogram.html)中,这些参数仍然像 NublicPablo 的回答中所示一样使用,或者我漏掉了什么吗? - Qaswed
如何加载和使用CDS在用户指南中有详细介绍:https://docs.bokeh.org/en/latest/docs/user_guide/data.html - bigreddot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接