Published
Edited
Aug 27, 2020
9 forks
27 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", "steelblue")
.attr("stroke-width", 10)
.attr("pointer-events", "all")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => x(d.value) - 0.75)
.attr("y", d => y(d.age))
.attr("width", 1.5)
.attr("height", y.bandwidth())
.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))
.range([margin.left + 10, width - margin.right])
Insert cell
y = d3.scaleBand()
.domain(data.map(d => d.age))
.rangeRound([margin.top, height - margin.bottom])
.padding(0.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
import {legend} from "@d3/color-legend"
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