在Markdown中嵌入bokeh图表

3

我没有找到有关如何将Bokeh绘图嵌入Markdown样式文档的任何文档。使用bokeh.embed.components中的script和div标签是否有简单的方法可以实现?


我想没有简单的解决方案,我在IPython笔记本(.ipynb或.html)中使用了bokeh图。我尝试过ipython nbconvert --to markdown,但是图表被破坏了。 - Sean
2个回答

1
如果你的Markdown风格支持<embed>标签,那么可以使用Bokeh的output_file()生成的.html文件来实现这一点。
在Python中:
from bokeh.plotting import figure, output_file, show

p = figure(title="example", x_axis_label='x', y_axis_label='y')

output_file("example.html")
show(p)  # Needed to actually save the file

在Markdown中:

<embed type="text/html" src="relative/path/to/example.html" width="600" height="400"></embed>

请注意,widthheight属性是必需的,因为它不会自动调整大小。
这种方法有一个小缺点,就是需要将绘图文件与Markdown一起保存。

在阅读了您的回答后,我脑海中灵光一闪。因为我在docs目录下添加了js/test.js文件,然后在mkdocs.yml中添加了extra_javascript: js/test.js,这样就可以将内容打印到控制台上了。而且使用嵌入标签,几乎可以实现任何事情! - Peter Moore

0

到目前为止,我发现唯一的方法是将图形渲染为图像,然后将其嵌入到Markdown中。

以下是一种方法:

首先将绘图导出为.png文件。因此,您需要安装:

conda install selenium phantomjs pillow

然后你可以使用:

from bokeh.plotting import figure
from bokeh.io import export_png

x = [1, 2, 3, 4, 5]
y = [6, 7, 3, 4, 5]
p = figure(title="example", x_axis_label='x', y_axis_label='y')
p.circle(x, y, legend="circles", line_width=2)

export_png(p, filename="bokeh_plot.png")

在 Markdown 中,您可以使用以下命令来显示图像。
![bokeh plot](bokeh_plot.png)

希望这有所帮助。

虽然这个回答在理论上可能可以回答问题,但最好还是在这里包含回答的关键部分,并提供链接作为参考。 - Anton Menshov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接