How to export svg or pdf from bokeh plot in google colab?

104 Views Asked by At

Goal is to save svg-figure with bokeh in google colab.

I followend the docs at https://colab.research.google.com/github/bebi103a/bebi103a.github.io/blob/master/lessons/06/intro_to_plotting_with_bokeh.ipynb

Result: RuntimeError, s. details below

p = bokeh.plotting.figure(
    width=400,
    height=300,
    x_axis_label="confidence when correct",
    y_axis_label="confidence when incorrect",
)
p.circle(
    source=df, 
    x="confidence when correct", 
    y="confidence when incorrect"
)

p.output_backend = "svg"
bokeh.io.export_svgs(p, filename="insomniac_confidence_correct.svg")


Then there is an error:
RuntimeError: To use bokeh.io image export functions you need selenium ('conda install selenium' or 'pip install selenium')
1

There are 1 best solutions below

0
golmschenk On

Example code exporting to SVG using Bokeh from Colab:

!pip install bokeh
!pip install google-colab-selenium

from bokeh.plotting import figure as Figure
from bokeh.io import export_svg
from google_colab_selenium import Chrome

example_figure = Figure()
example_figure.line(x=[0, 1, 2], y=[3, 5, 4])

webdriver = Chrome()
example_figure.output_backend = 'svg'
export_svg(example_figure, filename='example_figure.svg', webdriver=webdriver)

Bokeh expects a web browser to be available to create its figures. This can be a little tricky with how the virtual machine that runs the Colab instance is set up. You can manually install the correct browser packages on the virtual machine instance. Or, you can use something like the google-colab-selenium package to do the installation work for you. In the above code, google-colab-selenium provides its own installation of Chrome. The bokeh functions that expect a web browser let you pass which browser driver you want to use. So from there, you're just able to pass in the webdriver that google-colab-selenium provides.