chart = {
const width = 928;
const marginTop = 30;
const marginRight = 20;
const marginBottom = 0;
const marginLeft = 30;
const series = d3.stack()
.keys(d3.union(data.map(d => d.age)))
.value(([, D], key) => D.get(key).population)
.offset(d3.stackOffsetExpand)
(d3.index(data, d => d.state, d => d.age));
const height = series[0].length * 25 + marginTop + marginBottom;
const x = d3.scaleLinear()
// 💡 其实可以省略设置横坐标轴比例尺的定义域范围
// 因为标准化以后,水平堆叠条形图的横轴定义域范围就是 [0, 1] 与线性比例尺的默认定义域相同
.domain([0, d3.max(series, d => d3.max(d, d => d[1]))])
.range([marginLeft, width - marginRight]);
// 💡 设置纵坐标轴的比例尺,与**垂直堆叠条形图**的横坐标轴相对应
// 纵坐标轴的数据是条形图的各种分类,使用 d3.scaleBand 构建一个带状比例尺
const y = d3.scaleBand()
// 设置定义域范围(52 个州)
// 这里使用了 d3.groupSort() 先对 data 的数据点进行分组,再进行排序
// 第三个参数是分类依据,数据点按照 d.state 州的名称进行分组(用它作为各分组的 key)
// 第二个参数是分组数据的访问器,入参 D 是当前所遍历的分组
// D.find(d => d.age === "<10").population 是在该分组数据点(对象)中寻找到年龄段为 "<10" 的人口数量
// d3.sum(D, d => d.population) 是求出该分组所有数据点(对象)的属性 d.population 之和
// 最后返回两者之比,即年龄小于 10 岁的人口占该州总人口的比例,作为排序的依据
// ⚠️ 值得注意的是返回值添加了负号
// 由于默认按照升序排列,添加负号后就变成按照占比的降序排列,即 "<10" 人口数量较多的州排在前面
.domain(d3.groupSort(data, (D) => -D.find(d => d.age === "<10").population / d3.sum(D, d => d.population), d => d.state))
.range([marginTop, height - marginBottom]) // 这里的 height 高度是前面根据条形图的条带宽度和数量计算出来的
.padding(0.08); // 并设置间隔占据(柱子)区间的比例
const color = d3.scaleOrdinal()
.domain(series.map(d => d.key))
.range(d3.schemeSpectral[series.length])
.unknown("#ccc");
// A function to format the value in the tooltip.
const formatValue = x => isNaN(x) ? "N/A" : x.toLocaleString("en")
// Create the SVG container.
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto;");
// Append a group for each series, and a rect for each element in the series.
svg.append("g")
.selectAll()
.data(series)
.join("g")
.attr("fill", d => color(d.key))
.selectAll("rect")
.data(D => D.map(d => (d.key = D.key, d)))
.join("rect")
.attr("x", d => x(d[0]))
.attr("y", d => y(d.data[0]))
.attr("height", y.bandwidth())
.attr("width", d => x(d[1]) - x(d[0]))
.append("title")
.text(d => `${d.data[0]} ${d.key}\n${formatValue(d.data[1].get(d.key).population)}`);
/**
*
* 绘制坐标轴
*
*/
// 绘制横坐标轴
svg.append("g")
.attr("transform", `translate(0,${marginTop})`)
// 💡 横轴是一个刻度值朝上的坐标轴
// 并使用坐标轴对象的方法 axis.ticks() 设置坐标轴的刻度数量和刻度值格式
// 其中第一个参数用于设置刻度数量(这里设置的是预期值,并不是最终值,D3 会基于出入的数量进行调整,以便刻度更可视)
// 这里设置为 (width / 100) 基于页面的宽度来设置横坐标轴的预期刻度数量
// 而第二个参数用于设置刻度值格式,这里设置为 "%" 表示数值采用百分比表示
.call(d3.axisTop(x).ticks(width / 100, "%"))
.call(g => g.selectAll(".domain").remove());
// 绘制纵坐标轴
svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y).tickSizeOuter(0))
.call(g => g.selectAll(".domain").remove());
// Return the chart with the color scale as a property (for the legend).
return Object.assign(svg.node(), {scales: {color}});
}