从具有布局的图表创建独立的HTML

时间:2019-04-22 07:09:57

标签: python html bokeh

我想创建一个独立的HTML,其中包含基于布局的Bokeh的几个交互式图形(如果可能)。

我已经成功地将每个图表创建为自己的HTML或PNG。

我的图表是根据函数单独生成的。这是一个例子。

from bokeh.plotting import figure, output_file, show

def create_scatter():
    # output to static HTML file
    output_file("test_scatter.html")
    p = figure(plot_width=400, plot_height=400, title='This is a Scatter chart')

    # add a circle renderer with a size, color, and alpha
    p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
    p.title.text_font_style = "italic"

    # show the results
    show(p)

    # Attemp to return the chart
    return p


def create_line():
    # output to static HTML file
    output_file("line.html")
    p = figure(plot_width=400, plot_height=400, title='This is a Line chart')

    # add a line renderer
    p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2)
    p.title.text_color = "olive"
    p.toolbar.logo = None # Hide Bokeh Logo

    # show the results
    show(p)

    # Attemp to return the chart
    return p


def create_HTML(f1, f2):
    pass


def main():
    f1 = create_scatter()
    f2 = create_line()
    create_HTML(f1, f2)


if __name__ == '__main__':
    main()

但是,我找不到将它们全部组合到一个HTML文件中的方法。每个图表都有自己独特的标题,属性,图例和工具。

我的预期结果是基于布局创建一个独立的HTML,可以对其背景进行修改,等等。这是我的预期结果。

layout

提前谢谢


更新

我想我需要返回图的组成部分

script, div = components(p, CDN)
return script, div

然后我需要将它们放入HTML字符串中。最后,输出文件。

1 个答案:

答案 0 :(得分:1)

您已经给了自己答案。使用components是实现它的一种方法。 请查看Bokeh embed文档以了解所有选项。

如果您想要单个文件实现,则可以使用此方法(经过Bokeh 1.1.0测试):

from jinja2 import Template
from bokeh.plotting import figure
from bokeh.embed import file_html
from bokeh.models import Div, Paragraph, Row, Column
from bokeh.resources import CDN
from bokeh.util.browser import view

template = Template("""
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>{{ title if title else "Bokeh Plot" }}</title>
        {{ bokeh_css | safe }}
        {{ bokeh_js | safe }}
    </head>
    <body>
        {{ plot_div | safe }}
        {{ plot_script | safe }}
    </body>
</html> """)

p1 = figure(plot_width = 400, plot_height = 400)
p2 = figure(plot_width = 400, plot_height = 400)
p3 = figure(plot_width = 800, plot_height = 400)
p1.circle([1, 2, 3], [4, 5, 6])
p2.line([1, 2, 3], [4, 5, 6])
p3.line([1, 2, 3], [4, 5, 6])

html = file_html(Column(Row(p1, p2), Row(p3)), template = template, resources = CDN)

output_file = 'css_classes.html'
with open(output_file, 'w') as f:
    f.write(html)
view(output_file)

结果:

enter image description here