Published
Edited
Mar 3, 2021
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height));

svg.append("g")
.selectAll("g")
.data(data)
.join("g")
.attr("transform", d => `translate(${x0(d[groupKey])},0)`)
.selectAll("rect")
.data(d => {
let allVals = [];
let desiredKeys = keys
desiredKeys.forEach((dKey) => {
let val = {
key: dKey,
value: d[dKey]
}
allVals.push(val);
})
return allVals;
})
.join("rect")
.attr("x", d => x1(d.key))
.attr("y", d => y(d.value))
.attr("width", x1.bandwidth())
.attr("height", d => y(0) - y(d.value))
.attr("fill", d => color(d.key));

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

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

return svg.node();
}
Insert cell
legend = svg => {
const g = svg
.attr("transform", `translate(0,0)`)
.attr("text-anchor", "start")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g")
.data(color.domain().slice())
.join("g")
.attr("transform", (keys, i) => `translate(0,${i * 20})`);

g.append("rect")
.attr("x", 0)
.attr("width", 19)
.attr("height", 19)
.attr("fill", color);

g.append("text")
.attr("x", 22)
.attr("y", 9.5)
.attr("dy", "0.35em")
.text(d => d);
}
Insert cell
x0 = d3.scaleBand()
.domain(data.map(d => d[groupKey]))
.rangeRound([margin.left, width - margin.right])
.paddingInner(0.1)
Insert cell
x1 = d3.scaleBand()
.domain(keys)
.rangeRound([0, x0.bandwidth()])
.padding(0.05)
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data, d => d3.max(keys, key => d[key]))]).nice()
.rangeRound([height - margin.bottom, margin.top])
Insert cell
color = d3.scaleOrdinal()
.range(["#2a73b8","#9bc2e7"])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x0).tickFormat(i => 'HPI Quartile '+i).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
Insert cell
data = Object.assign(d3.csvParse(await FileAttachment("vaccines@2.csv").text(), d3.autoType), {y: "Percent population"})
Insert cell
groupKey = "HPIQUARTILE";
Insert cell
keys = ["FIRST_DOSE_RATIO","SECOND_DOSE_RATIO"];
Insert cell
margin = ({top: 10, right: 10, bottom: 80, left: 40})
Insert cell
height = 500
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