python-3.x - 如何直接更改散景`figure.renderers`的元素的`_property_values`?
问题描述
如何直接更改_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))
解决方案
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