Published
Edited
Oct 15, 2019
22 forks
Importers
38 stars
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 = 954
Insert cell
height = 720
Insert cell
fillColor = "#ddd"
Insert cell
lightColor = "#fff"
Insert cell
darkColor = "#000"
Insert cell
format = d3.format(",d")
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

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