Published
Edited
Aug 27, 2020
13 forks
Importers
15 stars
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("font-family", "sans-serif")
.attr("font-size", 10);

svg.append("g")
.selectAll("rect")
.data(data)
.join("rect")
.attr("fill", d => d3.schemeSet1[d.sex === "M" ? 1 : 0])
.attr("x", d => d.sex === "M" ? xM(d.value) : xF(0))
.attr("y", d => y(d.age))
.attr("width", d => d.sex === "M" ? xM(0) - xM(d.value) : xF(d.value) - xF(0))
.attr("height", y.bandwidth());

svg.append("g")
.attr("fill", "white")
.selectAll("text")
.data(data)
.join("text")
.attr("text-anchor", d => d.sex === "M" ? "start" : "end")
.attr("x", d => d.sex === "M" ? xM(d.value) + 4 : xF(d.value) - 4)
.attr("y", d => y(d.age) + y.bandwidth() / 2)
.attr("dy", "0.35em")
.text(d => d.value.toLocaleString());

svg.append("text")
.attr("text-anchor", "end")
.attr("fill", "white")
.attr("dy", "0.35em")
.attr("x", xM(0) - 4)
.attr("y", y(data[0].age) + y.bandwidth() / 2)
.text("Male");

svg.append("text")
.attr("text-anchor", "start")
.attr("fill", "white")
.attr("dy", "0.35em")
.attr("x", xF(0) + 24)
.attr("y", y(data[0].age) + y.bandwidth() / 2)
.text("Female");

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

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

return svg.node();
}
Insert cell
data = d3.csvParse(await FileAttachment("us-population.csv").text(), d3.autoType)
Insert cell
xM = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.rangeRound([width / 2, margin.left])
Insert cell
xF = d3.scaleLinear()
.domain(xM.domain())
.rangeRound([width / 2, width - margin.right])
Insert cell
y = d3.scaleBand()
.domain(data.map(d => d.age))
.rangeRound([height - margin.bottom, margin.top])
.padding(0.1)
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(g => g.append("g").call(d3.axisBottom(xM).ticks(width / 80, "s")))
.call(g => g.append("g").call(d3.axisBottom(xF).ticks(width / 80, "s")))
.call(g => g.selectAll(".domain").remove())
.call(g => g.selectAll(".tick:first-of-type").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${xM(0)},0)`)
.call(d3.axisRight(y).tickSizeOuter(0))
.call(g => g.selectAll(".tick text").attr("fill", "white"))
Insert cell
height = data.length / 2 * 25 + margin.top + margin.bottom
Insert cell
margin = ({top: 10, right: 0, bottom: 20, left: 0})
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