问题
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.
回答1:
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)
回答2:
As of Bokeh 0.12.13
there is no built-in UI mechanism for hiding the legend. Your best current bet would probably be to add a "show/hide legend" button that toggles .visible
on the legend.
回答3:
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
来源:https://stackoverflow.com/questions/48511036/is-there-a-way-to-interactively-turn-off-the-legend-in-a-python-bokeh-plot