Public
Edited
May 1, 2023
Insert cell
Insert cell
// Define the array of numbers
// Sort the numbers in descending order
numbers = [10, 60, 20, 30, 50, 55, 22, 27].sort((a, b) => b - a)
Insert cell
// Define the maximum diameter of a circle
maxDiameter = 100
Insert cell
// Use D3.js to scale the circle areas based on the size of the numbers
scale = d3
.scaleSqrt()
.domain([0, d3.max(numbers)])
.range([0, maxDiameter / 2])
Insert cell
scale(40)
Insert cell
// Calculate the total width of the circles
totalCircleWidth = numbers.reduce((acc, cur) => acc + scale(cur) * 2, 0)
Insert cell
// Calculate the spacing between the circles
remaningSpace = availableWidth - totalCircleWidth
Insert cell
spacing = remaningSpace / (numbers.length - 1)
Insert cell
Insert cell
canvas = {
const ctx = DOM.context2d(width, height);

const startOfAvailableWidth = width / 2 - availableWidth / 2;

ctx.strokeRect(
width / 2 - availableWidth / 2,
height / 2,
availableWidth,
50
);

// Draw the circles
let x = 0;
for (let i = 0; i < numbers.length; i++) {
console.log(x);
const diameter = scale(numbers[i]) * 2;
const radius = diameter / 2;
const y = height / 2;
ctx.beginPath();
ctx.arc(startOfAvailableWidth + x + radius, y, radius, 0, 2 * Math.PI);
ctx.stroke();
x += diameter + spacing;
}

return ctx.canvas;
}
Insert cell
height = 200
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