Public
Edited
Dec 7, 2022
Insert cell
Insert cell
Insert cell
d3 = require('d3@6')
Insert cell
height = 500
Insert cell
margin = ({
top: 10,
right: 10,
bottom: 40,
left: 35
})
Insert cell
Insert cell
data = FileAttachment("1940census@1.csv").csv()
Insert cell
import { Table } from "@observablehq/inputs"
Insert cell
Insert cell
Table(data, {
sort: "birth_year"
})
Insert cell
birth_years = d3.rollup(data, v => v.length, d => d.birth_year, d => d.gender)
Insert cell
aggregate = Array.from(birth_years, ([year, count]) => {
const obj = {};
for (const [gender, num] of count) {
obj.year = year;
obj[gender] = num;
}
return obj;
})
Insert cell
Table(aggregate, {
sort: "year"
})
Insert cell
md`## Define the X and Y Axis`
Insert cell
xDomain = aggregate.map(a => +a.year).sort()
Insert cell
xScale = d3
.scaleBand()
.domain(aggregate.map(d => d["year"]).sort())
.range([margin.left, width - margin.right - margin.left])
.padding(0.1)
Insert cell
x1 = d3
.scaleBand()
.domain(keys)
.rangeRound([0, xScale.bandwidth()])
.padding(0.05)
Insert cell
keys = Object.keys(aggregate[0]).slice(1)
Insert cell
yScale = d3
.scaleLinear()
.domain([0, d3.max(aggregate, d => d3.max(keys, key => d[key]))])
.nice()
.rangeRound([height - margin.bottom, margin.top])
Insert cell
xAxis = d3.axisBottom(xScale).tickSizeOuter(0)
Insert cell
yAxis = d3.axisLeft(yScale).tickSizeOuter(0)
Insert cell
color = d3.scaleOrdinal(d3.schemePastel1)
Insert cell
Insert cell
bars = {
const svg = d3.select(DOM.svg(width, height));

svg
.append("g")
.selectAll("g")
.data(aggregate)
.join("g")
.attr("transform", d => `translate(${xScale(d["year"])},0)`)
.selectAll("rect")
.data(d => keys.map(key => ({ key, value: d[key] })))
.join('rect')
.attr("x", d => x1(d.key))
.attr("y", d => yScale(d.value))
.attr("width", x1.bandwidth())
.attr("height", d => yScale(0) - yScale(d.value))
.attr("fill", d => color(d.key));

svg
.append('g')
.attr('class', 'x-axis')
.attr('transform', `translate(0,${height - margin.bottom})`)
.call(xAxis)
.selectAll("text")
.attr("x", 9)
.attr("dy", ".35em")
.attr("transform", "rotate(90)")
.style("text-anchor", "start");

svg
.append('g')
.attr('class', 'y-axis')
.attr('transform', `translate(${margin.left},0)`)
.call(yAxis);

return svg.node();
}
Insert cell
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