我在流函数内部的代码上苦苦挣扎,只将其传递给IPython一次。换句话说,从DynamicMap进行的display()
调用仅执行一次(click = hv.DynamicMap(interactive_click, streams=[SingleTap()])
)。
这只是一个简单的示例,但是在我的实际用例中,我那里需要执行display(Javascript(''))
代码。
# problem: display statement not returned to Jupyter Notebook
import numpy as np
import holoviews as hv
from holoviews import opts
from holoviews.streams import SingleTap
# from IPython.display import Javascript
hv.extension('bokeh')
# triggered when clicking on a plot
def interactive_click(x, y):
# problem: Only executed once
display("init")
if None not in [x, y]:
# problem: never executed, because `display()` is not passed to Jupyter Notebook
display(x)
else:
x = 0
return hv.VLine(x).opts(color='green')
# random plot: http://holoviews.org/reference/elements/bokeh/Image.html
ls = np.linspace(0, 10, 200)
xx, yy = np.meshgrid(ls, ls)
bounds=(-1,-1,1,1) # Coordinate system: (left, bottom, right, top)
img = hv.Image(np.sin(xx)*np.cos(yy), bounds=bounds)
# do something when clicked on plot
click = hv.DynamicMap(interactive_click, streams=[SingleTap()])
# show plot and trigger code on-press
img * click
display("init")
仅在输出单元格中显示一次,display(x)
从不显示(因为第一个输入为(None, None)
)。这只是一个简单的示例,但是在我的情况下,我想执行Javascript,但是只有在display()
输出传递到IPython内核时才能执行。
我知道代码已执行,因为图中的绿线移动了:
任何人都知道如何在给定的示例中使display(x)
显示输出(这意味着显示输出将传递到Jupyter Notebook中的IPython内核)?
答案 0 :(得分:0)
在pyviz Gitter上@philippjfr暗示,display_id
使解决方案成为可能。
我们在def interactive_click(x, y)
上方添加以下代码:
# create a display that we later update
display("None", display_id="click_value")
并将display(x)
更新为display(x, display_id="click_value")
如果现在单击图,我们将看到鼠标单击的x值“无”更改。
这也适用于Javascript:
display(Javascript('element.text("test");'), display_id="click_value")
完整代码:
# problem: display statement not returned to Jupyter Notebook
import numpy as np
import holoviews as hv
from holoviews import opts
from holoviews.streams import SingleTap
# from IPython.display import Javascript
hv.extension('bokeh')
# create a display that we later update
display("None", display_id="click_value")
# triggered when clicking on a plot
def interactive_click(x, y):
# problem: Only executed once
# display("init")
if None not in [x, y]:
# problem solved
display(x, display_id="click_value")
# display(Javascript('element.text("test");'), display_id="click_value")
else:
x = 0
return hv.VLine(x).opts(color='green')
# random plot: http://holoviews.org/reference/elements/bokeh/Image.html
ls = np.linspace(0, 10, 200)
xx, yy = np.meshgrid(ls, ls)
bounds=(-1,-1,1,1) # Coordinate system: (left, bottom, right, top)
img = hv.Image(np.sin(xx)*np.cos(yy), bounds=bounds)
# do something when clicked on plot
click = hv.DynamicMap(interactive_click, streams=[SingleTap()])
# show plot and trigger code on-press
img * click