Published
Edited
Mar 12, 2021
6 forks
Importers
11 stars
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis);

svg.append("g")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("pointer-events", "all")
.selectAll("circle")
.data(data)
.join("circle")
.attr("r", 3.5)
.attr("cx", d => x(d.value))
.attr("cy", d => y(d.age))
.append("title")
.text(d => `${d.name}
${(d.value * 100).toFixed(1)}% ${d.age}`);

return svg.node();
}
Insert cell
data = {
const data = d3.csvParse(await FileAttachment("us-population-state-age.csv").text(), d3.autoType);
const ages = data.columns.slice(1);
for (const d of data) d.total = d3.sum(ages, age => d[age]);
return ages.flatMap(age => data.map(d => ({name: d.name, age, value: d[age] / d.total})));
}
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data, d => d.value))
.rangeRound([margin.left + 10, width - margin.right])
Insert cell
y = d3.scalePoint()
.domain(data.map(d => d.age))
.rangeRound([margin.top, height - margin.bottom])
.padding(1)
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${margin.top})`)
.call(d3.axisTop(x).ticks(null, "%"))
.call(g => g.selectAll(".tick line").clone().attr("stroke-opacity", 0.1).attr("y2", height - margin.bottom - margin.top))
.call(g => g.selectAll(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.selectAll(".tick line").clone().attr("stroke-opacity", 0.1).attr("x2", width - margin.right - margin.left))
.call(g => g.selectAll(".domain").remove())
Insert cell
height = 280
Insert cell
margin = ({top: 20, right: 10, bottom: 10, left: 40})
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