为四边形字形创建图例标签 - 散景

Create Legend Label for Quad glyph - Bokeh

我有一个显示 2 个数据集的四元图。我想在情节中添加一个图例,但是我不确定如何使用 Quad 字形来做到这一点。

之前的示例使用了 'legend' 但是现在已弃用,我尝试使用 'legend_label' 然而这是行不通的。 我的最终目标是使用图例以交互方式显示两个数据集

    # Convert dataframe to column data source
    src1 = ColumnDataSource(Merged_Bins)
    src2 = ColumnDataSource(Merged_Bins)

    #------------------------------------------------------------------------------------------------
    # Plot Histogram using Bokeh plotting library
    #------------------------------------------------------------------------------------------------

    plot = figure(y_range=Range1d(start=0, end=Max_Histogram_Value),sizing_mode="scale_width",width=3000,height= 600,
                  title= "Histogram Plot",
                  x_axis_label="Time (ms)",
                  y_axis_label="Count",toolbar_location = "below")
    plot.yaxis.ticker = FixedTicker(ticks=list(tick_vals))


    glyph1=Quad(bottom=0, top='Delay1', left='left1',
              right='right1', fill_color='#FF7F00',
              line_color='black', fill_alpha=0.7,line_alpha=0.5,name="Option 2")
              
    glyph1_plot=plot.add_glyph(src1, glyph1)
    glyph2=Quad(bottom=0, top='Delay2', left='left2',
              right='right2', fill_color='#616261',
              line_color='#616261',line_alpha=0.1, fill_alpha=0.1,name="Original Design")
              
    plot.add_glyph(src2, glyph2)

    # Add hover tool for when mouse is over data
    hover1 = HoverTool(tooltips=[('Delay Envelope', '@Bin_interval'),('Count', '@Delay1'),('Count Original', '@Delay2')],mode='vline',renderers=[glyph1_plot])
    plot.add_tools(hover1)
    plot.legend.location = "top_left"
    plot.legend.click_policy="hide"
    # Set autohide to true to only show the toolbar when mouse is over plot
    plot.toolbar.autohide = True
    script, div = components(plot)
    show(plot)

如果您使用 Figure.quad 方法而不是使用显式创建的 Quad 实例手动调用 Figure.add_glyph,它工作得很好。所有 legen_* 参数都由 Figure class 的字形方法解析 - 字形 classes 本身根本不使用它们。

from bokeh.io import show
from bokeh.plotting import figure

p = figure()
p.quad(-1, 1, 1, -1, legend_label='Hello')
p.quad(1, 3, 3, 1, color='green', legend_label='there')

show(p)

或者,如果出于某种原因您确实需要手动方法,您还可以通过创建 Legend class 的实例并使用 Legend class 将其添加到图中来手动创建图例 Figure.add_layout.

此外,在一个不相关的说明上 - 你的情节看起来像是用 vbar 而不是 quad 创建的,因为所有的条形似乎都具有相同的宽度。如果是这样,也许在您的情况下使用 vbar 会更简单。