有没有一种交互式的方法可以关闭 Python `Bokeh` 图表中的图例?

3

如何在Bokeh图中隐藏图例

我了解如何通过编程方式关闭Bokeh绘图中的图例,但我想知道是否有一种交互式的方法来实现这一点? 有时,绘图图例中有多个项目,而图例占用了很多空间或房地产。 我想知道是否有一种点击图例以隐藏它或类似选项的方法。

我知道我可以通过代码影响图例的可见性:

 myPlot.legend.visible = False

然而我希望能够随意开关图例。

3个回答

4
您可以使用CustomJS。以下是一个示例,该示例可在DoubleTap事件上切换图例:
import numpy as np
from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh import events
from bokeh.models import CustomJS, ColumnDataSource

t = np.linspace(0, 4*np.pi, 100)
source = ColumnDataSource(data=dict(x=t, y1=np.sin(t), y2=np.cos(t)))
fig = figure(plot_height=250)
fig.line("x", "y1", source=source, legend="sin", line_color="red")
fig.line("x", "y2", source=source, legend="cos", line_color="green")

def show_hide_legend(legend=fig.legend[0]):
    legend.visible = not legend.visible

fig.js_on_event(events.DoubleTap, CustomJS.from_py_func(show_hide_legend))

show(fig)

1
有没有解决 BokehDeprecationWarning: 'from_py_func' is deprecated and will be removed in an eventual 2.0 release. Use CustomJS directly instead. 的方法?我尝试阅读了回调函数的相关文档,但似乎与图例的交互不是很直观。 - Rho Phi
为什么在CustomJS中将fig.legend[0]作为参数传递,而不是只传递fig.legend?如果只传递fig.legend,则交互不会发生。但是,fig.legend也显示为具有visible属性的Legend对象。我查看了文档 - 它说可分割的图例对象列表;不确定这是什么意思。 - Anirban Chakraborty

3

CustomJS.from_py_func 不再起作用,这应该可以解决问题。

    toggle_legend_js = CustomJS(args=dict(leg=p.legend[0]), code="""
         if (leg.visible) {
             leg.visible = false
             }
         else {
             leg.visible = true
         }
    """)
    

    p.js_on_event(events.DoubleTap, toggle_legend_js)  

其中p是您的图表


1
截至 Bokeh 0.12.13,没有内置的 UI 机制来隐藏图例。目前最好的选择可能是添加一个“显示/隐藏图例”按钮,该按钮可切换图例上的 .visible 属性。

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