Published
Edited
Aug 23, 2021
4 stars
Also listed in…
Sketches
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
getPrecisions = (n, bounds = [1 - maxLevels, 1]) =>
d3.range(...bounds).map((i) => {
const rounded = roundTo(n, i);
return {
i,
n: rounded,
range: getRange(rounded)
};
})
Insert cell
// round n to the ith place; 1 = 10s, 0 = 1s, -1 = 10th
roundTo = (n, i) =>
i > 0
? String(Math.round(n / 10 ** i) * 10 ** i)
: (Math.round(n * 10 ** -i) / 10 ** -i).toFixed(-i)
Insert cell
getRange = (n) => {
const [int, dec] = String(n).split(".");
const places = (!dec ? 0 : -dec.length) - 1;
const dif = 5 * 10 ** places;
return [+n - dif, +n + dif].map((d) => d.toFixed(-places));
}
Insert cell
initLevel = (g) =>
g
.call((g) =>
g
.append("path")
.attr("d", `M ${margin.left} 0 H ${w - margin.right}`)
.attr("stroke", "#eee")
)
.call((g) =>
g.append("path").attr("class", "range").attr("stroke", "black")
)
.call((g) =>
g
.append("text")
.attr("x", w - margin.right)
.attr("dx", "1em")
.attr("dy", "0.31em")
)
Insert cell
drawLevel = (xScale) => (g) =>
g
.call((g) => g.select("text").text((d) => d.n))
.call((g) =>
g
.select(".range")
.attr("d", (d) => `M ${xScale(d.range[0])} 0 H ${xScale(d.range[1])}`)
)
Insert cell
xScale = d3
.scaleLinear()
.domain([0, 2])
.range([margin.left, w - margin.right])
.clamp(true)
Insert cell
w = Math.min(width, 640)
Insert cell
maxLevels = 8
Insert cell
levelHeight = 20
Insert cell
margin = ({ top: 10, right: 80, bottom: 10, left: 0 })
Insert cell
height = levelHeight * maxLevels + margin.top + margin.bottom
Insert cell
import { tweet } from "@mbostock/tweet"
Insert cell
Insert cell
// truncTo = (n, i) => {
// const result = Math.trunc(n / 10 ** i) * 10 ** i;
// return i > 0 ? String(result) : result.toFixed(-i);
// }
Insert cell
// find pre-image "numerically" (instead of analytically)
d3.rollups(
d3
.range(0, 1, 0.01)
.slice(1)
.map((n) => [n, roundTo(n, -1)]),
(arr) => d3.extent(arr, (d) => d[0]),
(d) => d[1]
)
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