Published
Edited
Apr 15, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function solveLabelRotationLayout({
maxWidth: wm,
firstLabelWidth: l0,
labelHeight: h,
labelHeightMargin: m,
labelCount: n,
marginLeft: ml
}) {
const forwardDifferenceStep = 1e-6;
const iterMax = 20; // Given the high convergence rate of Newton-Raphson, 20 is probably unneccessarily much. But each iteration is very cheap.

let theta = 45;

const thetaAll = Array(iterMax).fill(0);
thetaAll[0] = theta;

const f = theta => {
const st = sind(theta);
const l = Math.max(ml, l0 * cosd(theta));
return st * (wm - l - h * st) - (n - 1) * (h + m);
};

for (let i = 1; i <= iterMax; i++) {
const value = f(theta);

// Forward difference approximation for the derivative
const value2 = f(theta + forwardDifferenceStep);
const derivativeApproximation = (value2 - value) / forwardDifferenceStep;

// The Newton-Raphson method update
theta = theta - value / derivativeApproximation;

// Clamp to the valid range
theta = clamp(theta, 0, 90);

thetaAll[i] = theta;
}

const convergenceThreshold = 1e-4; // Arbitrarily chosen, but see https://en.wikipedia.org/wiki/Numerical_differentiation#Step_size
const converged =
theta >= 0 && theta <= 90 && Math.abs(f(theta)) < convergenceThreshold;

mutable debugThetaAll = thetaAll;
const debugThetaCount = 100;
mutable debugThetaValues = Array.from({ length: debugThetaCount }, (_, i) => {
const k = i / (debugThetaCount - 1);
const theta = k * 90;
const value = f(theta);
const value2 = f(theta + forwardDifferenceStep);
const derivative = (value2 - value) / forwardDifferenceStep;

return {
theta,
value,
derivative
};
});

return {
converged,
theta,
labelSpacing: (h + m) / sind(theta),
marginLeft: Math.max(ml, l0 * cosd(theta) + (h / 2) * sind(theta)),
marginRight: (h * sind(theta)) / 2
};
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function clamp(x, a, b) {
return Math.max(a, Math.min(b, x));
}
Insert cell
Insert cell
defaultDomain = Array(labelCount)
.fill()
.map(() =>
Math.random()
.toString()
.substring(2, labelLength + 2)
.padStart(labelLength, "X")
)
.sort()
Insert cell
import { Range, Toggle } from "@observablehq/inputs"
Insert cell
import { vl } from '@vega/vega-lite-api-v5'
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