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!

Mark wijkhuizen
  • 373
  • 3
  • 10
  • It looks like there is not JS solution. The last call in [`export_png()` source](https://github.com/bokeh/bokeh/blob/664ead5306bba64609e734d4105c8aa8cfb76d81/bokeh/io/export.py#L243) 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. – mosc9575 Jun 08 '22 at 06:26
  • @mosc9575 You can now do this in JS – mrblue6 Apr 26 '23 at 15:52

1 Answers1

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.

mrblue6
  • 587
  • 2
  • 19