Published
Edited
May 28, 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);

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

const group = svg.append("g");

let rect = group.selectAll("rect");

return Object.assign(svg.node(), {
update(year) {
const dx = x.step() * (year - yearMin) / yearStep;

const t = svg.transition()
.ease(d3.easeLinear)
.duration(delay);

rect = rect
.data(data.filter(d => d.year === year), d => `${d.sex}:${d.year - d.age}`)
.join(
enter => enter.append("rect")
.style("mix-blend-mode", "darken")
.attr("fill", d => color(d.sex))
.attr("x", d => x(d.age) + dx)
.attr("y", d => y(0))
.attr("width", x.bandwidth() + 1)
.attr("height", 0),
update => update,
exit => exit.call(rect => rect.transition(t).remove()
.attr("y", y(0))
.attr("height", 0))
);

rect.transition(t)
.attr("y", d => y(d.value))
.attr("height", d => y(0) - y(d.value));

group.transition(t)
.attr("transform", `translate(${-dx},0)`);
}
});
}
Insert cell
chart.update(year)
Insert cell
delay = 250
Insert cell
data = Object.assign(d3.csvParse(await FileAttachment("icelandic-population.csv").text(), d3.autoType), {x: "← Age", y: "Population ↑"})
Insert cell
yearMin = d3.min(data, d => d.year)
Insert cell
yearStep = 1
Insert cell
x = d3.scaleBand()
.domain(Array.from(d3.group(data, d => d.age).keys()).sort(d3.ascending))
.range([width - margin.right, margin.left])
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([height - margin.bottom, margin.top])
Insert cell
color = d3.scaleOrdinal(["M", "F"], ["#4e79a7", "#e15759"])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x)
.tickValues(d3.ticks(...d3.extent(data, d => d.age), width / 40))
.tickSizeOuter(0))
.call(g => g.append("text")
.attr("x", margin.right)
.attr("y", margin.bottom - 4)
.attr("fill", "currentColor")
.attr("text-anchor", "end")
.text(data.x))
Insert cell
yAxis = g => g
.attr("transform", `translate(${width - margin.right},0)`)
.call(d3.axisRight(y).ticks(null, "s"))
.call(g => g.select(".domain").remove())
.call(g => g.append("text")
.attr("x", margin.right)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "end")
.text(data.y))
Insert cell
height = 500
Insert cell
margin = ({top: 20, right: 30, bottom: 34, left: 0})
Insert cell
d3 = require("d3@5", "d3-array@2")
Insert cell
import {Scrubber} from "@mbostock/scrubber"
Insert cell
import {swatches} 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