Published
Edited
Mar 12, 2021
2 forks
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
Insert cell
import { p5 } from "@tmcw/p5"
Insert cell
import {debounce} from "@mbostock/debouncing-input"
Insert cell
import {Range} from "@observablehq/inputs"
Insert cell
Insert cell
sin = x => Math.sin(x * Math.PI / 180)
Insert cell
map = (x, a, b, c, d) => ((x - a) / (b - a)) * (d - c) + c;
Insert cell
periodic = {
const rec = (a, b) => b ? a + rec(b-a) : a/2 + a/2 * Math.sin(now / 2000);
return rec;
}
Insert cell
Insert cell
// Return a function that runs fn() immediately, the first time. This handles thumbnails.
// Then run it only once the cell is visible.
async function whenVisible(fn) {
return async function(...args) {
if (this) await visibility();
return fn(...args);
};
}
Insert cell
function thisCached(key, thunk) {
if (!this) return thunk();
let cache = this.__thisCache;
if (!cache) {
this.__thisCache = cache = new Map();
}
if (cache.has(key)) {
return cache.get(key);
} else {
let value = thunk();
this.set(key, value);
return value;
}
}
Insert cell
sinWave = whenVisible(async function({
bias = 0,
amp = 1,
period = 1,
phase = 0,
yRange,
yScale = 1,
axes = true
}) {
const lineWidth = 2;
const range = yRange || [-100, 100];
const height = range[1] - range[0] + 10;
const xd = -range[1] + lineWidth;
const fn = x => bias + amp * sin(x / period + phase);
const y = x => yScale * fn(x);
const data = Array(width)
.fill()
.map((_, x) => [x, y(x)]);
const path = data
.map(p => `L${p.join(' ')}`)
.join(' ')
.replace('L', 'M');

function createSvg() {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
const g = svg.append("g").attr("transform", `translate(50, ${height / 2})`);

if (axes) {
const xscale = d3
.scaleLinear()
.domain([0, width])
.range([0, width]);
const x_axis = d3
.axisBottom()
.scale(xscale)
.ticks();
svg
.append("g")
.attr("transform", `translate(50, ${height / 2})`)
.call(x_axis);

const yscale = d3
.scaleLinear()
.domain([range[0] / yScale, range[1] / yScale])
.range(range);

const y_axis = d3
.axisLeft()
.scale(yscale)
.ticks();
g.call(y_axis);
}

g.append("path").attr("fill", "none");

return svg;
}

const svg = thisCached('svg', createSvg);
svg
.select("g")
.select("path")
.attr("d", path)
.attr("stroke-width", lineWidth)
.attr("stroke", "blue");

const fmt = d3.format("0.1f");
const phaseStr = d3.format("0.0f")( phase );
const eqn = `${fmt(amp)} * \\sin (x° / ${fmt(period)} + ${phaseStr}°) + ${fmt(bias)}`;
const code = `${fmt(amp)} * sin(x / ${fmt(period)} + ${phaseStr}) + ${fmt(bias)}`;

return md`
${svg.node()}
<table style="width: 100%">
<tr>
<th style="width: 5%"></th>
<th style="width: 25%">Math</th>
<th style="width: 25%">Code</th>
</tr>
<tr>
<td style="width: 5%"></td>
<td style="width: 25%">
${tex`y = ${simplifyEqn(eqn).replace(' * ', '')}`}</td>
<td style="width: 25%">
${md`\`\`\`javascript
let y = ${simplifyEqn(code)}
\`\`\``}
</td>
</tr>
</table>
`;
})
Insert cell
sinWave({ amp: 100, bias: -10 })
Insert cell
function sinWaveFill(phase = 0, suffix = "") {
const period = 1;
const height = 100;
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
const fn = x => 25 + 25 * sin(x / period + phase);
const pts = [
[0, height],
...Array(width)
.fill()
.map((_, x) => [x, fn(x)]),
[width, height]
];
const path = pts
.map(([x, y]) => `L${x},${y}`)
.join(" ")
.replace("L", "M");
svg
.append("path")
.attr("d", path)
.attr("fill", "blue");
const eqn = `map(sin(x / ${period.toFixed(
0
)}${suffix}), -1, 1, 0, ${height.toFixed(0)})`.replace(/ \/ 1(?=[^\d.])/, '');
return md`${svg.node()}
${`\`\`\`javascript
let y = ${eqn}
\`\`\``}`;
}
Insert cell
async function* bouncingBalls(ballSpecs = [{}, {}]) {
const specs = ballSpecs.map(spec => ({
period: 10,
phase: 0,
radius: 20,
color: "blue",
amp: 75,
...spec
}));
const height = Math.max(
...specs.map(({ radius, amp }) => 2 * (radius + amp))
);
const fn = ({ period, phase, amp }) =>
map(sin(new Date() / period + phase), 0, 1, height / 2, height / 2 + amp);
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
const circles = svg
.selectAll("circle")
.data(specs)
.enter()
.append("circle")
.attr("cx", (_, i) => ((i + 1) * width) / (specs.length + 1))
.attr("r", d => d.radius)
.attr("fill", d => d.color);

while (true) {
svg
.selectAll("circle")
.data(specs)
.attr("cy", fn);
yield svg.node();
}
}
Insert cell
async function* bouncingBallWithEqn({
amp = 150,
period = 10,
radius = 20
} = {}) {
const eqn = md`\`\`\`javascript
let y = map(sin(millis() / ${period.toFixed(0)}), -1, 1, 0, ${amp.toFixed(
0
)})\`\`\``;
const bs = await bouncingBalls([{ radius, period, amp }]);
const div = md`${(await bs.next()).value}\n${eqn}}`;

while (true) {
await bs.next();
yield div;
}
}
Insert cell
false &&
bouncingBalls([
{ phase: phase1, color: "red" },
{ phase: phase1, color: "blue" }
])
Insert cell
function* bounceTrail({ period = 10, radius = 10, height = 200 } = {}) {
const eqn = `\`\`\`javascript
map(sin(millis() / ${period.toFixed(0)}), -1, 1, 0, ${(
height -
2 * radius
).toFixed(0)})\`\`\``;
for (let elt of bouncingBallsWithTrails([{ period }])) {
yield md`${elt}
let y = ${eqn}
`;
}
}
Insert cell
bouncingBallsWithTrails = phases =>
p5(sketch => {
const height = 100;
const radius = 20;
const toObject = n =>
typeof n === 'number' || n.hasOwnProperty("value") ? { phase: n } : n;
const circles = phases.map(objOrValue => ({
period: 10,
phase: 0,
...toObject(objOrValue)
}));
let pg;
let pmillis;

const resolve = value =>
value.hasOwnProperty("value") ? value.value : value;

sketch.setup = () => {
sketch.createCanvas(width, height);
sketch.angleMode(sketch.DEGREES);
sketch.colorMode(sketch.HSB);
sketch.noStroke();

pg = sketch.createGraphics(width, height);
pg.background(255);
pg.colorMode(sketch.HSB);
pg.noStroke();

circles.forEach((obj, i) => {
obj.hue =
obj.hue || circles.length === 1
? 240
: sketch.map(i, 0, circles.length - 1, 0, 240);
});

pmillis = sketch.millis();
};

sketch.draw = () => {
const scroll = sketch.max(
-1,
sketch.round((sketch.millis() - pmillis) / (1000 / 30))
);
pmillis = sketch.millis();
pg.image(pg, -scroll, 0);
sketch.image(pg, 0, 0);

for (const { period, phase, hue, x } of circles) {
const x = width - radius;
const y = sketch.map(
sketch.sin(sketch.millis() / period + resolve(phase)),
-1,
1,
radius,
height - radius
);

pg.fill(hue, 100, 100, .005);
pg.circle(x, y, radius);
pg.fill(hue, 100, 100, .005);
pg.circle(x, y, radius * .8);

sketch.fill(hue, 100, 100);
sketch.circle(x, y, radius);
}
};
})
Insert cell
bouncingBallsWithTrails([0, { period: 90 }])
Insert cell
function simplifyEqn(eqn) {
return eqn
.replace(/\.0+(?=[^\d]|$)/g, '')
.replace(/ 1 \* /, ' ')
.replace(/^1 \* /, '')
.replace(' / 1 ', ' ')
.replace(/^0 \+ /, '')
.replace(/ \+ [−-]/g, ' - ')
.replace(/ \+ 0$/, '')
.replace(/ \+ 0°?(?=[^0-9.])/, '')
.replace(/sin \(([^\+/]+?)\)/, 'sin $1');
}
Insert cell
simplifyEqn("100.0 * sin(x / 1.0 + 0) + −10.0")
// simplifyEqn("x + −10.0")
// "x + 10.0".replace("-", " x-x ")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more