如何将bokeh图转换为BytesIO对象以使用base64模块对图进行编码

时间:2019-01-23 18:07:51

标签: base64 python-3.6 bokeh bytesio

我有一个plot的{​​{1}}对象,在其中绘制了bokeh曲线。

sin(x)

现在,我不想创建一个from math import * from io import BytesIO from bokeh.plotting import (figure, output_file, show) from bokeh.io import (export_png, export_svgs) import base64 import numpy as np plot = figure(plot_width=1000, plot_height=500) x = np.linspace(-2*np.pi, 2*np.pi, 1000) y = np.array([sin(i) for i in x]) plot.line(x, y, line_width=1) 对象,而不是使用某个名称将其保存到某个html文件中,以便进一步进行output_file('sine.html')编码。

我需要社区的帮助。

我想要的原因是在BytesIO()中,我可以将图像导出为base64对象,并使用它像这样在matplotlibBytesIO()应用中将其平滑地渲染回去,

Flask

我希望与Dash具有相同的适用性。

请指导我。

1 个答案:

答案 0 :(得分:0)

Bokeh在bokeh.io.export.get_screenshot_as_png中提供了此功能:

from bokeh.io.export import get_screenshot_as_png

img = get_screenshot_as_png(plot)

img是包含该图像的PIL图像实例。

离题:这也可以用于在JupyterLab中将图显示为PNG。只需致电get_screenshot_as_png(plot),您就完成了。