Published unlisted
Edited
Aug 19, 2020
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

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

const g = svg.append("g")
.attr("text-anchor", "end")
.style("font", "10px sans-serif")
.selectAll("g")
.data(data)
.join("g")
.attr("transform", (d, i) => `translate(0,${y(d.name)})`);

g.append("line")
.attr("stroke", "#aaa")
.attr("x1", d => x(d3.min(keys, k => d[k])))
.attr("x2", d => x(d3.max(keys, k => d[k])));

g.append("g")
.selectAll("circle")
.data(d => d3.cross(keys, [d]))
.join("circle")
.attr("cx", ([k, d]) => x(d[k]))
.attr("fill", ([k]) => color(k))
.attr("r", 3.5);

g.append("text")
.attr("dy", "0.35em")
.attr("x", d => x(d3.min(keys, k => d[k])) - 6)
.text((d, i) => d.name);

return Object.assign(svg.node(), {
update(names) {
y.domain(names);

g.transition()
.delay((d, i) => i * 10)
.attr("transform", d => `translate(0,${y(d.name)})`)
}
});
}
Insert cell
update = {
const index = d3.range(data.length);
const order = primary === "name" ? d3.ascending : d3.descending;
index.sort((i, j) => order(data[i][primary], data[j][primary]));
chart.update(d3.permute(data.map(d => d.name), index));
}
Insert cell
data = d3.csvParse(await FileAttachment("us-population-state-age.csv").text(), (d, i, columns) => (d3.autoType(d), d.total = d3.sum(columns, c => d[c]), columns.slice(1).forEach(c => d[c] /= d.total), d))
Insert cell
keys = data.columns.slice(1)
Insert cell
x = d3.scaleLinear()
.domain([0, d3.max(data, d => d3.max(keys, k => d[k]))])
.rangeRound([margin.left, width - margin.right])
Insert cell
y = d3.scalePoint()
.domain(data.map(d => d.name).sort(d3.ascending))
.rangeRound([margin.top, height - margin.bottom])
.padding(1)
Insert cell
color = d3.scaleOrdinal()
.domain(keys)
.range(d3.schemeSpectral[keys.length])
.unknown("#ccc")
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))
.call(g => g.selectAll(".domain").remove())
Insert cell
height = data.length * 16
Insert cell
margin = ({top: 20, right: 10, bottom: 10, left: 10})
Insert cell
d3 = require("d3@5")
Insert cell
import {legend} from "@d3/color-legend"
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