Public
Edited
Mar 13, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
data = {
const data = d3.csvParseRows(source, ([name, value, color]) => ({name, value: !value || isNaN(value = +value) ? undefined : value, color}));
if (sorted) data.sort((a, b) => b.value - a.value);
return data;
}
Insert cell
pack = data => {
let alt = d3.median(data, d => d.value);
if (!alt) alt = 1;
return d3.pack()
.size([width, height])
.padding(3)
(d3.hierarchy({children: data})
.sum(d => isNaN(d.value) ? alt : d.value));
}
Insert cell
width = 780
Insert cell
height = 500
Insert cell
fillColor = "#ddd"
Insert cell
lightColor = "#fff"
Insert cell
darkColor = "#000"
Insert cell
format = d3.format("$.2s")
Insert cell
function fit(text, value) {
let line;
let lineWidth0 = Infinity;
const lineHeight = 12;
const targetWidth = Math.sqrt(measureWidth(text.trim()) * lineHeight);
const words = text.split(/\s+/g); // To hyphenate: /\s+|(?<=-)/
if (!words[words.length - 1]) words.pop();
if (!words[0]) words.shift();
const lines = [];
for (let i = 0, n = words.length; i < n; ++i) {
let lineText1 = (line ? line.text + " " : "") + words[i];
let lineWidth1 = measureWidth(lineText1);
if ((lineWidth0 + lineWidth1) * 0.4 < targetWidth) {
line.width = lineWidth0 = lineWidth1;
line.text = lineText1;
} else {
lineWidth0 = measureWidth(words[i]);
line = {width: lineWidth0, text: words[i]};
lines.push(line);
}
}
if (value !== undefined) lines.push({width: measureWidth(value), text: value});
let radius = 0;
for (let i = 0, n = lines.length; i < n; ++i) {
const dy = (Math.abs(i - n / 2 + 0.5) + 0.5) * lineHeight;
const dx = lines[i].width / 2;
radius = Math.max(radius, Math.sqrt(dx ** 2 + dy ** 2));
}
return {lines, radius};
}
Insert cell
measureWidth = {
const context = document.createElement("canvas").getContext("2d");
return text => context.measureText(text).width;
}
Insert cell
function autosize(svg) {
document.body.appendChild(svg);
const box = svg.getBBox();
document.body.removeChild(svg);
svg.setAttribute("viewBox", `${box.x - 1} ${box.y - 1} ${box.width + 2} ${box.height + 2}`);
return svg;
}
Insert cell
import {rasterize, serialize} from "@mbostock/saving-svg"
Insert cell
d3 = require("d3@5")
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