Bokeh - Exporting Plots



In addition to subcommands described above, Bokeh plots can be exported to PNG and SVG file format using export() function. For that purpose, local Python installation should have following dependency libraries.

PhantomJS

PhantomJS is a JavaScript API that enables automated navigation, screenshots, user behavior and assertions. It is used to run browser-based unit tests. PhantomJS is based on WebKit providing a similar browsing environment for different browsers and provides fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. In other words, PhantomJS is a web browser without a graphical user interface.

Pillow

Pillow, a Python Imaging Library (earlier known as PIL) is a free library for the Python programming language that provides support for opening, manipulating, and saving many different image file formats. (including PPM, PNG, JPEG, GIF, TIFF, and BMP.) Some of its features are per-pixel manipulations, masking and transparency handling, image filtering, image enhancing, etc.

The export_png() function generates RGBA-format PNG image from layout. This function uses Webkit headless browser to render the layout in memory and then capture a screenshot. The generated image will be of the same dimensions as the source layout. Make sure that the Plot.background_fill_color and Plot.border_fill_color are properties to None.

from bokeh.io import export_png
export_png(plot, filename = "file.png")

It is possible that HTML5 Canvas plot output with a SVG element that can be edited using programs such as Adobe Illustrator. The SVG objects can also be converted to PDFs. Here, canvas2svg, a JavaScript library is used to mock the normal Canvas element and its methods with an SVG element. Like PNGs, in order to create a SVG with a transparent background,the Plot.background_fill_color and Plot.border_fill_color properties should be to None.

The SVG backend is first activated by setting the Plot.output_backend attribute to "svg".

plot.output_backend = "svg"

For headless export, Bokeh has a utility function, export_svgs(). This function will download all of SVG-enabled plots within a layout as distinct SVG files.

from bokeh.io import export_svgs
plot.output_backend = "svg"
export_svgs(plot, filename = "plot.svg")
Advertisements