Skip to content

patch matplotlib’s show #294

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 23, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 49 additions & 4 deletions src/py.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,62 @@ import {pyodide as Pyodide} from "./dependencies.js";

export default async function py(require) {
const pyodide = await (await require(Pyodide.resolve())).loadPyodide();
let patch; // a promise for patching matplotlib (if needed)
return async function py(strings, ...values) {
let globals = {};
const globals = {};
const code = strings.reduce((code, string, i) => {
if (!(i in values)) return code + string;
const name = `_${i}`;
globals[name] = values[i];
return code + string + name;
}, "");
globals = pyodide.toPy(globals);
await pyodide.loadPackagesFromImports(code);
const value = await pyodide.runPythonAsync(code, {globals});
const imports = findImports(pyodide, code);
if (imports.includes("matplotlib") && !patch) await (patch = patchMatplotlib(require, pyodide));
if (imports.length) await pyodide.loadPackagesFromImports(code);
const value = await pyodide.runPythonAsync(code, {globals: pyodide.toPy(globals)});
return pyodide.isPyProxy(value) ? value.toJs() : value;
};
}

// https://github.com/pyodide/pyodide/blob/1624e4a62445876a2d810fdbfc9ddb69a8321a8e/src/js/api.ts#L119-L125
function findImports(pyodide, code) {
const imports = pyodide.pyodide_py.find_imports(code);
try {
return imports.toJs();
} finally {
imports.destroy();
}
}

// Overrides matplotlib’s show function to return a DIV such that when used as
// the last expression in an Observable cell, the inspector will display it.
async function patchMatplotlib(require, pyodide) {
require.resolve("[email protected]/css/font-awesome.min.css").then(href => {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = href;
document.head.appendChild(link);
});
await pyodide.loadPackage("matplotlib");
await pyodide.runPythonAsync(`from matplotlib import pyplot as plt
from js import document

_show = plt.show

def create_root_element(self):
div = document.createElement("div")
document.body.appendChild(div)
return div

def show(self):
c = plt.gcf().canvas
c.create_root_element = create_root_element.__get__(c, c.__class__)
_show()
div = c.get_element("")
if (div.parentNode == document.body):
document.body.removeChild(div)
return div

plt.show = show.__get__(plt, plt.__class__)
`);
}