iamseeley-pyodidedatavis.web.val.run
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
export const pyodideExample = () => {
const html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Data Vis with Pyodide</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/pyodide/v0.25.1/full/pyodide.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<h1>Data Vis using Python in WebAssembly</h1>
<input type="text" id="numbers" placeholder="Enter a list of numbers, separated by commas">
<button id="plot">Plot</button>
<div id="plotContainer"></div>
<script>
async function main() {
let pyodide = await loadPyodide();
await pyodide.loadPackage('numpy');
console.log('Pyodide is ready to use!');
pyodide.runPython(\`
import numpy as np
import json
def plot_numbers(numbers):
x = np.array(numbers)
y_square = x ** 2
y_cube = x ** 3
data = {
'x': x.tolist(),
'y_square': y_square.tolist(),
'y_cube': y_cube.tolist()
}
return json.dumps(data)
\`);
return pyodide;
}
const pyodide = main();
const plotButton = document.getElementById('plot');
const numbersInput = document.getElementById('numbers');
const plotContainer = document.getElementById('plotContainer');
plotButton.addEventListener('click', async () => {
const numbers = numbersInput.value.split(',').map(Number);
const plotData = await pyodide.then(pyodide => pyodide.runPython(\`plot_numbers(\${JSON.stringify(numbers)})\`));
const data = JSON.parse(plotData);
const trace1 = {
x: data.x,
y: data.y_square,
mode: 'lines+markers',
name: 'Square'
};
const trace2 = {
x: data.x,
y: data.y_cube,
mode: 'lines+markers',
name: 'Cube'
};
const layout = {
title: 'Numbers and Their Powers',
xaxis: { title: 'Number' },
yaxis: { title: 'Value' }
};
Plotly.newPlot(plotContainer, [trace1, trace2], layout);
});
</script>
</body>
</html>
`;
return new Response(html, {
headers: {
"Content-Type": "text/html",
},
});
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
May 18, 2024