Public
Edited
Aug 1, 2023
63 forks
48 stars
Insert cell
Insert cell
Insert cell
chart = {

const color = d3.scaleOrdinal()
.domain(data.map(d => d[2]))
.range(d3.schemeCategory10);

const zoom = d3.zoom()
.on("zoom", zoomed);

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

const g = svg.append("g")
.attr("fill", "none")
.attr("stroke-linecap", "round");

g.selectAll("path")
.data(data)
.join("path")
.attr("d", d => `M${x(d[0])},${y(d[1])}h0`)
.attr("stroke", d => color(d[2]));

const gx = svg.append("g")
.attr("transform", `translate(0,${height})`);
const xAxis = (g, x) => g
.call(d3.axisTop(x).ticks(12))
.call(g => g.select(".domain").attr("display", "none"));

const gy = svg.append("g");
const yAxis = (g, y) => g
.call(d3.axisRight(y).ticks(12 * k))
.call(g => g.select(".domain").attr("display", "none"));

svg.call(zoom.transform, viewof transform.value);

function zoomed({transform}) {
g.attr("transform", transform).attr("stroke-width", 5 / transform.k);
gx.call(xAxis, transform.rescaleX(x));
gy.call(yAxis, transform.rescaleY(y));
}

return Object.assign(svg.node(), {
update(transform) {
svg.transition()
.duration(1500)
.call(zoom.transform, transform);
}
});
}
Insert cell
chart.update(transform)
Insert cell
data = {
const random = d3.randomNormal(0, 0.2);
const sqrt3 = Math.sqrt(3);
return [].concat(
Array.from({length: 300}, () => [random() + sqrt3, random() + 1, 0]),
Array.from({length: 300}, () => [random() - sqrt3, random() + 1, 1]),
Array.from({length: 300}, () => [random(), random() - 1, 2])
);
}
Insert cell
transforms = [["Overview", d3.zoomIdentity]].concat(d3.groups(data, d => d[2]).map(([key, data]) => {
const [x0, x1] = d3.extent(data, d => d[0]).map(x);
const [y1, y0] = d3.extent(data, d => d[1]).map(y);
const k = 0.9 * Math.min(width / (x1 - x0), height / (y1 - y0));
const tx = (width - k * (x0 + x1)) / 2;
const ty = (height - k * (y0 + y1)) / 2;
return [`Cluster ${key}`, d3.zoomIdentity.translate(tx, ty).scale(k)];
}))
Insert cell
x = d3.scaleLinear()
.domain([-4.5, 4.5])
.range([0, width])
Insert cell
y = d3.scaleLinear()
.domain([-4.5 * k, 4.5 * k])
.range([height, 0])
Insert cell
k = height / width
Insert cell
height = 600
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