这将有助于维护共享的“x”数据源列,如果将glyphs分配为变量并赋予名称属性。 remove函数使用NaN填充适当的“y”列,而restore函数用原始值替换NaN。
这些函数需要导入numpy和bokeh GlyphRenderer。我不确定在简单的可见/隐藏选项下是否值得采用此方法,但无论如何,我还是发布了它,以防在其他用例中有所帮助。
要删除或恢复的glyphs由包含在列表中的glyph名称引用。
src_dict = source.data.copy()
def remove_glyphs(figure, glyph_name_list):
renderers = figure.select(dict(type=GlyphRenderer))
for r in renderers:
if r.name in glyph_name_list:
col = r.glyph.y
r.data_source.data[col] = [np.nan] * len(r.data_source.data[col])
def restore_glyphs(figure, src_dict, glyph_name_list):
renderers = figure.select(dict(type=GlyphRenderer))
for r in renderers:
if r.name in glyph_name_list:
col = r.glyph.y
r.data_source.data[col] = src_dict[col]
例子:
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
from bokeh.models import Range1d, ColumnDataSource
from bokeh.models.renderers import GlyphRenderer
import numpy as np
output_notebook()
p = figure(plot_width=200, plot_height=150,
x_range=Range1d(0, 6),
y_range=Range1d(0, 10),
toolbar_location=None)
source = ColumnDataSource(data=dict(x=[1, 3, 5],
y1=[1, 1, 2],
y2=[1, 2, 6],
y3=[1, 3, 9]))
src_dict = source.data.copy()
line1 = p.line('x', 'y1',
source=source,
color='blue',
name='g1',
line_width=3)
line2 = p.line('x', 'y2',
source=source,
color='red',
name='g2',
line_width=3)
line3 = p.line('x', 'y3',
source=source,
color='green',
name='g3',
line_width=3)
print(source.data)
show(p)
输出:
{'x': [1, 3, 5], 'y1': [1, 1, 2], 'y2': [1, 2, 6], 'y3': [1, 3, 9]}
![enter image description here](https://istack.dev59.com/7zEJv.webp)
remove_glyphs(p, ['g1', 'g2'])
print(source.data)
show(p)
输出:
{'x': [1, 3, 5], 'y1': [nan, nan, nan], 'y2': [nan, nan, nan], 'y3': [1, 3, 9]}
![enter image description here](https://istack.dev59.com/ujx3B.webp)
restore_glyphs(p, src_dict, ['g1', 'g3'])
print(source.data)
show(p)
“g3”已经在图表上,不受影响。
输出:
{'x': [1, 3, 5], 'y1': [1, 1, 2], 'y2': [nan, nan, nan], 'y3': [1, 3, 9]}
![enter image description here](https://istack.dev59.com/eeAIB.webp)
restore_glyphs(p, src_dict, ['g2'])
print(source.data)
show(p)
输出:
{'x': [1, 3, 5], 'y1': [1, 1, 2], 'y2': [1, 2, 6], 'y3': [1, 3, 9]}
![enter image description here](https://istack.dev59.com/5U9Ko.webp)
F.renderers.remove(line2)
(renderers 表现为一个列表,所以您可以像操作任何 Python 列表一样操作它),但我想优化很小,因为您的数据仍将存储在源中。这只会节省 Bokeh 不必解析该图形并检查其可见性。虽然我从未对其进行过分析,也不太熟悉内部情况,无法确定。如果您对其进行了分析,请告诉我们! - Alex