如何直接更改bokeh`figure.renderers`元素的`_property_values`?

问题描述 投票:0回答:1

如何直接更改散景_property_values的元素的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))
python-3.x bokeh updates ipywidgets
1个回答
0
投票

Bigreddot为我指明了正确的方向:我不必直接更新p,但可以用来生成p的元素(此处为Span)。这样,我找到了代码所在的this question:更新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 does not have variables。因此,我们可以通过更改x来更改元素y

x = ['alice']
y = x
y[0] = 'bob'
x  # is now ['bob] too
© www.soinside.com 2019 - 2024. All rights reserved.