【问题标题】:Is there a way to interactively turn off the legend in a python `Bokeh` plot有没有办法以交互方式关闭 python `Bokeh` 图中的图例
【发布时间】:2020-08-13 17:13:14
【问题描述】:

Hide legend in bokeh plot

所以我知道谁以编程方式关闭 Bokeh 图中的图例,但是我想知道是否有办法以交互方式执行此操作?有时我在情节图例中有许多项目,而图例会占用大量空间或空间。我想知道是否有办法点击图例来隐藏它,或者一些这样的选项?

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

 myPlot.legend.visible = False

但是我希望能够根据需要打开和关闭图例。

【问题讨论】:

    标签: python plot legend bokeh


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

    • BokehDeprecationWarning: 'from_py_func' is deprecated and will be removed in an eventual 2.0 release. Use CustomJS directly instead. 有修复方法吗?我曾尝试阅读 about callbacks,但与图例交互似乎并不简单。
    【解决方案2】:

    从 Bokeh 0.12.13 开始,没有用于隐藏图例的内置 UI 机制。您当前最好的选择可能是添加一个“显示/隐藏图例”按钮,在图例上切换.visible

    【讨论】:

      【解决方案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 是你的figure

      【讨论】:

        猜你喜欢
        • 2011-11-08
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        • 2015-04-24
        • 2021-06-26
        • 2019-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多