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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With