Published
Edited
Aug 26, 2021
1 star
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
svg.append("g")
.call(xAxis);
svg.append("g")
.selectAll("circle")
.data(dodge(data, {r: d => r(getR(d)), x: d => x(getX(d))}))
.join("circle")
.attr("cx", d => d.x)
.attr("cy", d => height - margin.bottom - d.r - d.y)
.attr("r", d => d.r)
.append("title")
.text(d => d.data.name);

return svg.node();
}
Insert cell
dodge(data, {r: d => r(getR(d)), x: d => x(getX(d))})
Insert cell
function dodge(data, {r = d => d, x = d => d} = {}) {
const circles = data
.map((d, i, data) => ({x: +x(d, i, data), r: +r(d, i, data), data: d}))
.sort((a, b) => b.r - a.r); // sort by radius instead of X value for more "stable" looking layout
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, r) {
let a = head;
while (a) {
if ((a.r + r) ** 2 - 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 - (head.r + b.r) ** 2) head = head.next;

// Choose the minimum non-intersecting tangent.
if (intersects(b.x, b.y = 0, b.r)) {
let a = head;
b.y = Infinity;
do {
let y = a.y + Math.sqrt((a.r + b.r) ** 2 - (a.x - b.x) ** 2);
if (y < b.y && !intersects(b.x, y, b.r)) 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
data = (await FileAttachment("cars-2.csv").csv({typed: true})).map(({Name: name, Weight_in_lbs: weight, Year: year, Horsepower: hp}) => ({name, weight: +weight, year: +year, hp: +hp}))
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data, getX))
.range([margin.left, width - margin.right])
Insert cell
r = d3.scaleLinear()
.domain(d3.extent(data, getR))
.range([0, 10])
Insert cell
getX = d => d.weight
Insert cell
getR = d => d.hp
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0))
Insert cell
height = 240
Insert cell
margin = ({top: 20, right: 20, bottom: 30, left: 20})
Insert cell
d3 = require("d3@6")
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