Public
Edited
Sep 23
13 forks
Importers
6 stars
Insert cell
Insert cell
chart = {
const width = 928;
const height = 160;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 20;
const marginLeft = 20;
const radius = 3;
const padding = 1.5;

const x = d3.scaleLinear()
.domain(d3.extent(cars, d => d["weight (lb)"]))
.range([marginLeft, width - marginRight]);

const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto;");
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0));
svg.append("g")
.selectAll()
.data(dodge(cars, {radius: radius * 2 + padding, x: d => x(d["weight (lb)"])}))
.join("circle")
.attr("cx", d => d.x)
.attr("cy", d => height - marginBottom - radius - padding - d.y)
.attr("r", radius)
.append("title")
.text(d => d.data.name);

return svg.node();
}
Insert cell
function dodge(data, {radius = 1, x = d => d} = {}) {
const radius2 = radius ** 2;
const circles = data.map((d, i, data) => ({x: +x(d, i, data), data: d})).sort((a, b) => a.x - b.x);
const epsilon = 1e-3;
let head = null, tail = null;

// Returns true if circle ⟨x,y⟩ intersects with any circle in the queue.
function intersects(x, y) {
let a = head;
while (a) {
if (radius2 - epsilon > (a.x - x) ** 2 + (a.y - y) ** 2) {
return true;
}
a = a.next;
}
return false;
}

// Place each circle sequentially.
for (const b of circles) {

// Remove circles from the queue that can’t intersect the new circle b.
while (head && head.x < b.x - radius2) head = head.next;

// Choose the minimum non-intersecting tangent.
if (intersects(b.x, b.y = 0)) {
let a = head;
b.y = Infinity;
do {
let y = a.y + Math.sqrt(radius2 - (a.x - b.x) ** 2);
if (y < b.y && !intersects(b.x, y)) b.y = y;
a = a.next;
} while (a);
}

// Add b to the queue.
b.next = null;
if (head === null) head = tail = b;
else tail = tail.next = b;
}

return circles;
}
Insert cell
Insert cell
Plot.plot({
height: 165,
x: {line: true},
marks: [
Plot.dotX(cars, Plot.dodgeY({
x: "weight (lb)",
sort: "weight (lb)",
title: "name",
fill: "currentColor"
}))
]
})
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