Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to interactively turn off the legend in a python `Bokeh` plot

Hide legend in bokeh plot

So I understand who to programmatically turn off the legend in a Bokeh plot, however I was wondering if there is a way to do this interactively? Sometimes I have a number of items in a plot legend, and the legend takes up lot of space or real estate. I was wondering if there is a way to click on the legend to hide it, or some such option?

I know I can affect the legend visibility through the code:

 myPlot.legend.visible = False

However I would to be able to turn the legend on and off as I wish.

like image 201
krishnab Avatar asked Oct 18 '25 14:10

krishnab


2 Answers

You can use CustomJS, here is an example that toggle legend on DoubleTap event:

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)
like image 71
HYRY Avatar answered Oct 21 '25 04:10

HYRY


As CustomJS.from_py_func is no longer working this should make the trick

    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)  

where p is your figure

like image 27
Rho Phi Avatar answered Oct 21 '25 04:10

Rho Phi