Published
Edited
Sep 15, 2022
1 fork
Importers
92 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
graph = createGraph(nodes)
Insert cell
run0 = shortest_tree({
origins: [nodes.length - 1],
graph,
step: stepbystep ? 1 : 0
})
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
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
color = d3
.scaleSequential(interpolateRoma)
.domain([0, width])
.nice()
Insert cell
euclidian = (p, q) => Math.hypot(p[0] - q[0], p[1] - q[1])
Insert cell
function draw_points(context, points, opts = {}) {
const TAU = 2 * Math.PI;
const {radius = 3, fill = "white", stroke = "black", lineWidth = 1} = opts;
context.beginPath();
points.forEach(p => {
context.moveTo(p[0] + radius, p[1]);
context.arc(p[0], p[1], radius, 0, TAU);
});
if (fill) {
context.fillStyle = fill;
context.fill();
}
if (stroke && lineWidth) {
context.lineWidth = lineWidth;
context.strokeStyle = stroke;
context.stroke();
}
}
Insert cell
function draw_special_points(context, points) {
draw_points(context, points, {fill: "orange"});
}
Insert cell
function draw_starting_points(context, points, opts = {}) {
const radius = 5;
draw_points(context, points, {radius, lineWidth: 1.5});
context.font = "14px Arial";
context.textBaseline = "middle";
if (points.length > 1 && opts.labels)
points.forEach((p, i) => {
context.fillText(
String.fromCodePoint("A".charCodeAt(0) + i),
p[0] + radius + 4,
p[1]
);
});
}
Insert cell
function draw_connections(context, nodes, run) {
context.beginPath();
run.predecessor.forEach((d, i) => {
if (d > -1) {
context.moveTo(...nodes[i]);
context.lineTo(...nodes[d]);
}
});
context.lineWidth = 0.5;
context.strokeStyle = "white";
context.stroke();
}
Insert cell
function draw_voronoi_cells(context, nodes, run) {
const width = parseInt(context.canvas.style.width),
height = (context.canvas.height / context.canvas.width) * width,
voronoi = d3.Delaunay.from(nodes).voronoi([0, 0, width, height]);

let i = 0;
for (const cell of voronoi.cellPolygons()) {
context.strokeStyle = context.fillStyle = color(run.cost[i]);
context.beginPath(),
voronoi.renderCell(i, context),
context.fill(),
context.stroke();
i++;
}
}
Insert cell
function draw_contours(context, nodes, run, opts = {}) {
const path = d3.geoPath().context(context),
contours = d3.tricontour().thresholds(opts.quick ? 50 : 300)(
nodes.map((d, i) => [d[0], d[1], run.cost[i]]).filter(d => isFinite(d[2]))
);

context.lineWidth = 1;
for (const c of contours) {
context.strokeStyle = context.fillStyle = color(c.value);
context.beginPath();
path(c);
context.fill();
context.stroke();
}

if (opts.lines) {
context.strokeStyle = "white";
context.fillStyle = "white";
context.textAlign = "center";
context.font = "12px Arial";
context.globalAlpha = 1;
for (const c of contours) {
if (c.value % 20 === 0) {
context.lineWidth = c.value % 100 === 0 ? 1 : 0.5;
if (opts.labels && !opts.quick && c.value % 100 === 0) {
drawLabels(context, c);
} else {
context.beginPath();
path(c);
context.stroke();
}
}
}
}
}
Insert cell
// adapted from https://observablehq.com/@fil/contour-labels-canvas
function drawLabels(context, contour) {
const width = parseInt(context.canvas.style.width),
height = (context.canvas.height / context.canvas.width) * width,
scale = 1,
path = d3.geoPath().context(context);

const threshold = contour.value,
labels = [],
steps = 30;

contour.coordinates.forEach(polygon =>
polygon.forEach((ring, j) => {
const p = ring.slice(1, Infinity),
// best number of steps to divide ring.length
possibilities = d3.range(steps, steps * 1.4),
scores = possibilities.map(d => -((p.length - 1) % d)),
n = possibilities[d3.scan(scores)],
// best starting point: bottom for first rings, top for holes
start = 1 + (d3.scan(p.map(xy => (j === 0 ? -1 : 1) * xy[1])) % n),
margin = 2;

if (p.length < 15) return; // no label on small contours

p.forEach((xy, i) => {
if (
i % n === start &&
xy[0] > margin &&
xy[0] < width - margin &&
xy[1] > margin &&
xy[1] < height - margin
) {
const a = (i - 2 + p.length) % p.length,
b = (i + 2) % p.length,
dx = p[b][0] - p[a][0],
dy = p[b][1] - p[a][1];
if (dx === 0 && dy === 0) return;

labels.push({
threshold, // value
xy: xy.map(d => scale * d),
angle: Math.atan2(dy, dx),
text: `${threshold}`
});
}
});
})
);

// create the mask for this threshold:
// the full rectangle minus a rectangle around each label
context.save();
context.beginPath();
context.moveTo(0, 0),
context.lineTo(width, 0),
context.lineTo(width, height),
context.lineTo(0, height),
context.lineTo(0, 0);
const arc = d3.arc();
for (const label of labels) {
for (let i = 0; i < 2 * Math.PI; i += 0.2) {
const pos = [Math.cos(i) * 13, -Math.sin(i) * 10],
c = Math.cos(label.angle),
s = Math.sin(label.angle);
context[i === 0 ? "moveTo" : "lineTo"](
label.xy[0] + pos[0] * c - pos[1] * s,
label.xy[1] + pos[1] * c + pos[0] * s
);
}
}
// context.stroke(); // uncomment to see the mask
context.clip();

// draw white contour for this threshold
context.beginPath();
path(contour);
context.stroke();

// draw labels for this threshold
context.restore();
for (const label of labels) {
addlabel(context, label);
}

function addlabel(context, label) {
context.save();
context.translate(...label.xy);
context.rotate(label.angle + (Math.cos(label.angle) < 0 ? Math.PI : 0));
context.fillText(label.text, -1, 4);
context.restore();
}
}
Insert cell
// adapted from https://observablehq.com/@d3/hello-d3-drag
drag = (agents, draw, end) => {
// When starting a drag gesture, move the subject to the top and mark it as active.
function dragstarted() {
d3.select(this).style("cursor", "grabbing");
}

// When dragging, update the subject’s position.
async function dragged() {
const agent = d3.event.subject;
agent[0] = Math.max(0, Math.min(width, d3.event.x));
agent[1] = Math.max(0, Math.min(height, d3.event.y));
await draw(true);
}

// When ending a drag gesture, mark the subject as inactive again.
function dragended() {
// d3.event.subject.active = false;
d3.select(this).style("cursor", "grab");
if (end) end();
draw();
}

function dragsubject(event) {
const radius = 30;
if (!event) event = d3.event;
let subject = null;
let distance = radius * 1.5;

for (const c of agents) {
let d = Math.hypot(event.x - c[0], event.y - c[1]);
if (d < distance) {
distance = d;
subject = c;
}
}
return subject;
}

return function(sel) {
sel
.style("cursor", "pointer")
.call(
d3
.drag()
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
)
.on("mousemove", function() {
const m = d3.mouse(this),
subject = dragsubject({ x: m[0], y: m[1] });
d3.select(this).style("cursor", subject ? "grab" : "pointer");
});
};
}
Insert cell
rng = Math.random
Insert cell
import { pick2d } with { rng } from "@fil/2d-point-distributions"
Insert cell
height = 400
Insert cell
d3 = require("d3@5", "d3-delaunay@5", "d3-tricontour@0.1")
Insert cell
import { legend } from "@d3/color-legend"
Insert cell
import { checkbox } from "@jashkenas/inputs"
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