首页 > 解决方案 > 带有流的 HoloViews DynamicMap 仅将显示输出一次传递给 IPython

问题描述

我正在努力处理流函数中的代码,它只传递给 IPython 一次。换句话说,display()来自 DynamicMap 的调用只执行一次 ( 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 内核时才能执行。

我知道代码已执行,因为图中的绿线移动:

HoloViews 绘图交互

问题

任何人都知道我如何display(x)在给定的示例中进行显示输出(意味着显示输出被传递到 Jupyter Notebook 中的 IPython 内核)?

标签: python-3.xjupyter-notebookbokehholoviews

解决方案


display_id正如@philippjfr 在pyviz Gitter上所暗示的那样,该解决方案成为可能。

我们在上面添加以下代码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

推荐阅读