Published
Edited
Jun 19, 2021
1 star
Insert cell
Insert cell
import { py, pyodide } from '@gnestor/pyodide'
Insert cell
pyodide.runPython(`import sys
sys.version`)
Insert cell
pyodide.runPython(`from js import document
document.body.children`)
Insert cell
pyodide.runPython(`button = document.createElement('button')

count = 0
button.textContent = str(count)

def onclick(event):
global count
count += 1
button.textContent = str(count)

button.addEventListener('click', onclick)

button`)
Insert cell
pyodide.runPython(`from js import document

canvas = document.createElement('canvas')
canvas.setAttribute('width', 450)
canvas.setAttribute('height', 300)
context = canvas.getContext("2d")
context.strokeStyle = "#df4b26"
context.lineJoin = "round"
context.lineWidth = 5
pen = False
lastPoint = (0, 0)

def onmousemove(e):
global lastPoint
if pen:
newPoint = (e.offsetX, e.offsetY)
context.beginPath()
context.moveTo(lastPoint[0], lastPoint[1])
context.lineTo(newPoint[0], newPoint[1])
context.closePath()
context.stroke()
lastPoint = newPoint
def onmousedown(e):
global pen, lastPoint
pen = True
lastPoint = (e.offsetX, e.offsetY)
def onmouseup(e):
global pen
pen = False

canvas.addEventListener('mousemove', onmousemove)
canvas.addEventListener('mousedown', onmousedown)
canvas.addEventListener('mouseup', onmouseup)

canvas`)
Insert cell
foo = py`class Foo:
def __init__(self, val):
self.val = val

foo = Foo(42)

foo`
Insert cell
foo.val
Insert cell
data = {
await pyodide.loadPackage('numpy');
return py`import numpy as np
x = np.linspace(0, 2.0 * np.pi, 100)
y = np.sin(x)
x, y`;
}
Insert cell
{
const [x, y] = data;
const div = document.createElement('div');
Plotly.plot(div, [{ y, x }]);
return div;
}
Insert cell
plot = {
await data;
await pyodide.loadPackage('matplotlib');
return py`from matplotlib import pyplot as plt
import types
import io
import base64

def show(self):
buf = io.BytesIO()
self.savefig(buf, format='png')
buf.seek(0)
img_str = 'data:image/png;base64,' + base64.b64encode(buf.read()).decode('UTF-8')
el = document.createElement('img')
el.src = img_str
return el

plt._show = types.MethodType(plt.show, plt)
plt.show = types.MethodType(show, plt)

plt.figure()
plt.plot(x, y)

plt`;
}
Insert cell
plot.show()
Insert cell
Plotly = require("https://cdn.plot.ly/plotly-latest.min.js")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more