Public
Edited
Jul 21, 2020
6 forks
3 stars
Insert cell
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(0,${y0(d[groupKey])})`)
.selectAll("rect")
.data(d => keys.map(key => ({key, value: d[key]})))
.join("rect")
.attr("x", d => x(0))
.attr("y", d => y1(d.key))
.attr("height", y1.bandwidth())
.attr("width", d => x(d.value) - x(0))
.attr("fill", d => color(d.key));

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

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

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

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

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

g.append("text")
.attr("x", -24)
.attr("y", 9.5)
.attr("dy", "0.35em")
.text(d => d);
}
Insert cell
y0 = d3.scaleBand()
.domain(data.map(d => d[groupKey]))
.rangeRound([margin.top, height - margin.bottom])
.paddingInner(0.1)
Insert cell
y1 = d3.scaleBand()
.domain(keys)
.rangeRound([y0.bandwidth(), 0])
.padding(0.05)
Insert cell
x = d3.scaleLinear()
.domain([0, d3.max(data, d => d3.max(keys, key => d[key]))]).nice()
.rangeRound([margin.left, width - margin.right])
Insert cell
color = d3.scaleOrdinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
.call(d3.axisBottom(x).ticks(3, "s"))
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 15)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y0).ticks(null, "s"))
.call(g => g.select(".domain").remove())
Insert cell
data = Object.assign(d3.csvParse(await FileAttachment("data.csv").text(), d3.autoType), {y: "Population"})
Insert cell
groupKey = data.columns[0]
Insert cell
keys = data.columns.slice(1)
Insert cell
margin = ({top: 10, right: 150, bottom: 20, left: 40})
Insert cell
height = 500
Insert cell
d3 = require("d3@5")
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