保存后尝试显示散景图会引发错误

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

我创建了两种装饰品:

from bokeh.plotting import show
from bokeh.io import save

def savable(function):
    def wrapper(
            *args,
            save_path: Optional[str] = None,
            **kwargs):
        result = function(*args, **kwargs)
        if save_path:
            print(f"saved to {save_path}")
            save(result, save_path)
        return result

    return wrapper


def showable(function):
    def wrapper(
            *args,
            show: bool = True,
            **kwargs):
        result = function(*args, **kwargs)
        if show and result is not None:
            show(result)
        return result

    return wrapper

我用它们两个装饰了一些返回散景图的函数。 当订单是:

@showable
@savable

我收到错误

Models must be owned by only a single document

我尝试将顺序更改为:

@savable
@showable

并且没有错误。

我需要在保存后显示绘图的选项,所以我试图理解为什么它在初始顺序中不起作用。

python plot bokeh
1个回答
0
投票

在您的代码中,您多次使用某些模型(例如标题),这会导致错误。

我想引用这个问题

在没有看到实际笔记本的情况下很难说出任何具体内容。一些通用建议:

  • 不要重复使用变量
  • 不要在文档之间重复使用 Bokeh 模型
  • 不要在单元的顶层创建模型。相反,将它们全部包装在一个函数中并调用该函数(类似于 bokehserve 内部的做法)

事实是,调用

save
show
可能会发生冲突。如果你确定你只保存了一个图形,如果它没有显示在笔记本中,那么它就可以工作了。

我建议仅在包装器上实现,如下所示:

from bokeh.plotting import figure, show, output_notebook
from bokeh.io import export_png, export_svgs, output_file, reset_output, save

def output_helper(function):
    def wrapper(
            *args,
            show_plot: bool = True,
            save_path: str = None,
            **kwargs):
        p = function(*args, **kwargs)
        if save_path and save_path.endswith('png'):
            export_png(p, filename=save_path)
        elif save_path and save_path.endswith('html'):
            output_file(save_path, mode="inline")
            if not show_plot:
                save(p, filename=save_path, title="Plot", resources=None)
        if show_plot:
            output_notebook()
            show(p)
            reset_output()
        return p

    return wrapper

使用示例可以是

@output_helper
def create_plot():
    p = figure()
    p.circle([1,2,3], [1,2,3])
    return p

create_plot(save_path='a.html')

显示笔记本中的图形并创建一个 html 文件。

© www.soinside.com 2019 - 2024. All rights reserved.