我了解如何通过编程方式关闭Bokeh
绘图中的图例,但我想知道是否有一种交互式的方法来实现这一点? 有时,绘图图例中有多个项目,而图例占用了很多空间或房地产。 我想知道是否有一种点击图例以隐藏它或类似选项的方法。
我知道我可以通过代码影响图例的可见性:
myPlot.legend.visible = False
然而我希望能够随意开关图例。
我了解如何通过编程方式关闭Bokeh
绘图中的图例,但我想知道是否有一种交互式的方法来实现这一点? 有时,绘图图例中有多个项目,而图例占用了很多空间或房地产。 我想知道是否有一种点击图例以隐藏它或类似选项的方法。
我知道我可以通过代码影响图例的可见性:
myPlot.legend.visible = False
然而我希望能够随意开关图例。
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)
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
是您的图表
BokehDeprecationWarning: 'from_py_func' is deprecated and will be removed in an eventual 2.0 release. Use CustomJS directly instead.
的方法?我尝试阅读了回调函数的相关文档,但似乎与图例的交互不是很直观。 - Rho PhiCustomJS
中将fig.legend[0]
作为参数传递,而不是只传递fig.legend
?如果只传递fig.legend
,则交互不会发生。但是,fig.legend
也显示为具有visible
属性的Legend
对象。我查看了文档 - 它说可分割的图例对象列表;不确定这是什么意思。 - Anirban Chakraborty