starboard-python
Version:
Python cells for Starboard Notebook
43 lines (38 loc) • 1.45 kB
text/typescript
/**
* Matplotlib currently creates a dom element which never gets attached to the DOM.
* Without a way to specify our own DOM node creation function, we override it here - saving us from shipping our own matplotlib package.
*/
export function patchMatplotlib(module: { runPython: (code: string) => any }) {
// Switch to simpler matplotlib backend https://github.com/jupyterlite/jupyterlite/blob/main/packages/pyolite-kernel/py/pyolite/pyolite/patches.py
module.runPython(`import os
os.environ["MPLBACKEND"] = "AGG"`);
module.runPython(`import matplotlib
import matplotlib.pyplot
from pyodide import create_proxy
from js import drawPyodideCanvas
def show():
canvas = matplotlib.pyplot.gcf().canvas
canvas.draw()
pixels = canvas.buffer_rgba().tobytes()
width, height = canvas.get_width_height()
drawPyodideCanvas(pixels, width, height)
return None
def showUint8():
pixels_proxy = None
pixels_buf = None
try:
canvas = matplotlib.pyplot.gcf().canvas
canvas.draw()
pixels = canvas.buffer_rgba().tobytes()
pixels_proxy = create_proxy(pixels)
pixels_buf = pixels_proxy.getBuffer("u8clamped")
drawPyodideCanvas(pixels)
finally:
if pixels_proxy:
pixels_proxy.destroy()
if pixels_buf:
pixels_buf.release()
matplotlib.pyplot.show = show
`);
}