Published
Edited
Jan 3, 2022
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
{
const svg = d3.select(DOM.svg(size + margin * 2, size + margin * 2));

svg
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", size + margin * 2)
.attr("height", size + margin * 2)
.style("fill", "#eee");

const g = svg
.append("g")
.attr(
"transform",
`translate(${margin - stepSize / 2}, ${margin - stepSize / 2})`
);

const pathStr = pts.reduce((acc, cur) => {
return acc + `L${cur[0]} ${cur[1]}`;
}, `M${size / 2} ${size / 2}`);

g.append("path")
.attr("d", pathStr)
.style("stroke", "#ccc")
.style("stroke-width", 1.2)
.style("fill", "none");

if (r == "Dots") {
g.selectAll("circle")
.data([[size / 2, size / 2]].concat(pts.filter((d, i) => isPrime(i + 1))))
.enter()
.append("circle")
.attr("cx", (d) => d[0])
.attr("cy", (d) => d[1])
.attr("r", 5)
.style("fill", "#005c8c")
.style("opacity", 0.9);
} else {
g.selectAll("text")
.data(pts)
.enter()
.append("text")
.attr("x", (d) => d[0])
.attr("y", (d) => d[1] + 3)
.text((d, i) => i + 1)
.style("text-anchor", "middle")
.style("font-weight", (d, i) => (isPrime(i + 1) ? 600 : 300))
.style("font-size", 11)
.style("fill", (d, i) => (isPrime(i + 1) ? "#005c8c" : "#aaa"))
.style("font-family", "sans-serif");
}

return svg.node();
}
Insert cell
pts = {
let memo = [size / 2, size / 2];
let pts = [memo];
let sign = 1;
let step = 1;
while (step < 26) {
d3.range(step).forEach(d => {
const x = memo[0] + sign * stepSize;
memo = [x, memo[1]];
pts.push(memo);
});
d3.range(step).forEach(d => {
const y = memo[1] + sign * stepSize;
memo = [memo[0], y]
pts.push(memo);
});
sign = -1 * sign;
step += 1;
}
d3.range(step - 1).forEach(d => {
const x = memo[0] + sign * stepSize;
memo = [x, memo[1]];
pts.push(memo);
});
return pts;
}
Insert cell
// https://stackoverflow.com/questions/40200089/javascript-number-prime-test
isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num !== 1 && num !== 0;
}
Insert cell
Insert cell
Insert cell
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