![](/img/trans.png)
[英]set title of a python `bokeh` plot figure from outside of the `figure()` function
[英]deleting line from figure in bokeh
我是Bokeh的新手。 我創建了一個小部件,當我單擊一個復選框時,我希望能夠在散景圖中添加/刪除一行。 我有20個這樣的復選框,我不想重新繪制整個圖,只是刪除1行,如果未選中復選框。
這是通過回調完成的,我可以訪問圖形對象。 我想有辦法做這樣的事情:
F=figure()
F.line('x', 'y', source=source, name='line1')
F.line('x', 'z', source=source, name='line2')
%%in callback
selected_line_name = 'line1' # this would be determined by checkbox
selected_line = F.children[selected_line_name]
delete(selected_line)
但是,我無法弄清楚如何1)從其父對象訪問一個字形2)刪除一個字形
我嘗試設置數據源'y'= [],但由於所有列數據源必須大小相同,這將刪除所有圖...
有幾種方法:
# Keep the glyphs in a variable:
line2 = F.line('x', 'z', source=source, name='line2')
# or get the glyph from the Figure:
line2 = F.select_one({'name': 'line2'})
# in callback:
line2.visible = False
如果將字形指定為變量並給定name屬性,這將用於維護共享的“x”數據源列。 remove函數用nans填充相應的'y'列,restore函數用原始值替換nans。
這些函數需要numpy和bokeh GlyphRenderer導入。 我不確定這個方法是否值得,因為簡單的可見開/關選項,但我發布它無論如何,以防萬一這有助於其他一些用例。
要刪除或恢復的字形由列表中包含的字形名稱引用。
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]}
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]}
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]}
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]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.