0

How to save plots in Bokeh JS as PNG programmatically?

The documentation gives the following example in Python:

from bokeh.io import export_png

export_png(plot, filename="plot.png")

I could however not find an example on how to programmatically save plots in JavaScript.

The use case is to generate plots in the back-end and use them in automatically generated reports.

Any tips on saving plots in Bokeh JS programmatically are welcome!

2
  • It looks like there is not JS solution. The last call in export_png() source is Image() which comes from another Python package named PIL. E.g. that the png generation was not implemendet by bokeh and is pure python based. Commented Jun 8, 2022 at 6:26
  • @mosc9575 You can now do this in JS Commented Apr 26, 2023 at 15:52

1 Answer 1

1

Very late answer but there is now a workaround to do this: https://discourse.bokeh.org/t/trying-to-print-export-bokehjs-plot-how-can-i-do-this-how-to-use-export-png/10074/5

The BokehJS plots have a save button which runs with this code:

async save(name: string): Promise<void> {
  const blob = await this.parent.export().to_blob()
  const link = document.createElement("a")
  link.href = URL.createObjectURL(blob)
  link.download = name // + ".png" | "svg" (inferred from MIME type)
  link.target = "_blank"
  link.dispatchEvent(new MouseEvent("click"))
}

You can access plots with this line (ie. replace this.parent.export() with this: 0 is to get the first plot

Object.values(Bokeh.index)[0].export

I have this function tied to my own button so I can do some other operations as well as save the plot.

Edit: BokehJS plots in simple terms get drawn onto a canvas HTML element, the toolbar is then absolutely positioned on top of this somehow. So it saves the plot the same way you could save a regular canvas element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.