首页 > 解决方案 > 在 Bokeh 中使用 HoverTool 嵌入具有相对路径的本地图像

问题描述

我正在尝试创建一个图,当您将鼠标悬停在字形上时,它会显示类似文档中此蛇示例的图像:

如果我提供包含绝对路径的 pandas 数据框系列/DataSourceColumn @images,则代码在使用 运行时可以正常工作show,但如果我使用当前工作目录 (subfolder_from_cwd/filename.png) 的相对路径,则使用show. 我的目标是制作一个包含数据的可移植 html 文件,但似乎save output_savehtml 函数的绝对路径不会嵌入图像,所以我需要使用相对路径。

我努力了:

但我不确定还能尝试什么。

谢谢你的帮助。

def make_bokeh_plot(dataframe, title):
    def style(p):
        p.title.align = 'center'
        p.title.text_font_size = '18pt'
        p.xaxis.axis_label_text_font_size = '12pt'
        p.xaxis.major_label_text_font_size = '12pt'
        p.yaxis.axis_label_text_font_size = '12pt'
        p.yaxis.major_label_text_font_size = '12pt'

        return p



    #make a histogram, keeping the image path
    arr_df, frequencies, edges  = make_histogram_df(dataframe.score.values, bins=100)

    #Make a list of the paths indexes by histrogram index bins
    img_path_series=make_img_path_series(edges,dataframe)
    #merge it with arr_df
    arr_df["images"]=img_path_series
    print(arr_df["images"].head())

    #Make df into a bokeh friendly format 
    arr_src = ColumnDataSource(arr_df)

    # Set up the figure same as before
    p = figure(plot_width = 500, plot_height = 500, title = title,
                x_range=(0, 1),
              x_axis_label = 'Scores', y_axis_label = 'Count')

    # Add a quad glyph with source this time
    p.quad(bottom=0, top='count', left='left', right='right', source=arr_src,
           fill_color='red', line_color='black')

    # Add style to the plot
    styled_p = style(p)

    # Add a hover tool referring to the formatted columns
    hover = HoverTool(tooltips = [('Delay', '@f_interval'),
                                  ('Count', '@f_count'),
                                  ('Image', '@images')])

    # src="file://@images" height="200" alt="@imgs" width="200"
    #file://
    hover = HoverTool(tooltips ="""
            <div>
                <div>
                    <img
                        src="file://@images" alt="@imgs" 
                        style="float: left; margin: 0px 15px 15px 0px;"
                        border="2"
                    ></img>
                </div>
                <div>
                    <span style="font-size: 15px;">@f_count @f_interval</span>
                    <span style="font-size: 10px; color: #696;">($x, $y)</span>
                </div>
            """)


    # Add the hover tool to the graph
    styled_p.add_tools(hover)

    show(p)

    return p

通过bokeh serve --show script.py图像运行服务器时,即使使用绝对路径也不会显示。同样,在将其作为服务器运行时,我尝试了各种编写相对路径的方法。

标签: pythonplotbokeh

解决方案


这是行不通的。浏览器不会file://从通过 HTTP 加载的页面加载 URL。为了使这项工作,图像文件必须从真实的 Web 服务器提供并通过http://URL 加载。


推荐阅读