如何直接更改_property_values
bokeh元素的figure.renderers
?我了解到的元素renderers
具有ID,因此我希望做类似的事情renderers['12345']
。但是由于它是一个列表(更精确地说是一个PropertyValueList),所以不起作用。相反,我发现的唯一解决方案是遍历列表,将正确的元素存储在新的指针(?)中,修改指针,从而修改原始元素。
这是我的玩具示例,其中直方图中的垂直线根据某些小部件的值进行更新:
import hvplot.pandas
import ipywidgets as widgets
import numpy as np
from bokeh.io import push_notebook, show, output_notebook
from bokeh.models import Span
from bokeh.plotting import figure
%matplotlib inline
hist, edges = np.histogram([1, 2, 2])
p = figure()
r = p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:])
vline = Span(location=0, dimension='height')
p.renderers.extend([vline])
def update_hist(x):
myspan = [x for x in p.renderers if x.id==vline.id][0]
myspan._property_values['location'] = x
show(p, notebook_handle=True)
widgets.interact(update_hist, x = widgets.FloatSlider(min=1, max=2))
Bigreddot为我指明了正确的方向:我不必p
直接进行更新,但是需要使用用于生成的元素p
(此处为Span
)。这样,我发现了 这个问题,代码在哪里解决了:update vline.location
。
完整代码:
import hvplot.pandas
import ipywidgets as widgets
import numpy as np
from bokeh.io import push_notebook, show, output_notebook
from bokeh.models import Span
from bokeh.plotting import figure
%matplotlib inline
hist, edges = np.histogram([1, 2, 2])
p = figure()
r = p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:])
vline = Span(location=0, dimension='height')
p.renderers.extend([vline])
show(p, notebook_handle=True)
def update_hist(x):
vline.location = x
push_notebook()
widgets.interact(update_hist, x = widgets.FloatSlider(min=1, max=2, step = 0.01))
作为Python的初学者,我仍然经常监督Python没有变量。因此,我们可以x
通过更改来更改元素y
。
x = ['alice']
y = x
y[0] = 'bob'
x # is now ['bob] too