交互式图例

传说 添加到Bokeh绘图中的图形可以交互,这样单击或点击图例条目将隐藏或禁用绘图中相应的字形。这些模式通过设置 click_policy 属性 Legend 要么 "hide""mute" .

注解

交互式图例仅适用于“每字形”图例。分组图例尚不支持下面描述的功能。

隐藏字形

有时,通过单击 Legend . 在Bokeh,这可以通过设置图例来实现 click_policy 属性到 "hide" 如下图所示:

import pandas as pd

from bokeh.palettes import Spectral4
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT

p = figure(plot_width=800, plot_height=250, x_axis_type="datetime")
p.title.text = 'Click on legend entries to hide the corresponding lines'

for data, name, color in zip([AAPL, IBM, MSFT, GOOG], ["AAPL", "IBM", "MSFT", "GOOG"], Spectral4):
    df = pd.DataFrame(data)
    df['date'] = pd.to_datetime(df['date'])
    p.line(df['date'], df['close'], line_width=2, color=color, alpha=0.8, legend_label=name)

p.legend.location = "top_left"
p.legend.click_policy="hide"

output_file("interactive_legend.html", title="interactive_legend.py example")

show(p)

静音字形

其他时候,图例交互最好将字形静音,而不是完全隐藏它。在这种情况下,设置 click_policy 属性到 "mute" . 此外,还需要指定“静音glyph”的视觉属性。一般来说,这与 选定和未选定图示符悬停检查 . 在下面的例子中, muted_alpha=0.2muted_color=color 被传递给 circle 指定应使用低alpha静音图示符绘制静音线。

import pandas as pd

from bokeh.palettes import Spectral4
from bokeh.plotting import figure, show
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT

p = figure(plot_width=800, plot_height=250, x_axis_type="datetime")
p.title.text = 'Click on legend entries to mute the corresponding lines'

for data, name, color in zip([AAPL, IBM, MSFT, GOOG], ["AAPL", "IBM", "MSFT", "GOOG"], Spectral4):
    df = pd.DataFrame(data)
    df['date'] = pd.to_datetime(df['date'])
    p.line(df['date'], df['close'], line_width=2, color=color, alpha=0.8,
           muted_color=color, muted_alpha=0.2, legend_label=name)

p.legend.location = "top_left"
p.legend.click_policy="mute"

show(p)