Public
Edited
Apr 16, 2024
Insert cell
Insert cell
Insert cell
chart = {
// 设置一些关于尺寸的参数(除了 svg 的高度,它由条带的数量来决定)
const width = 928;
const marginTop = 30;
const marginRight = 20;
const marginBottom = 0;
const marginLeft = 30;

/**
*
* 对数据进行转换
*
*/
// Determine the series that need to be stacked.
const series = d3.stack()
.keys(d3.union(data.map(d => d.age))) // distinct series keys, in input order
.value(([, D], key) => D.get(key).population) // get value for each series key and stack
// 💡 设置堆叠基线函数,这里采用 D3 所提供的一种默认基线函数 d3.stackOffsetExpand
// 对数据进行标准化(相当于把同一个条带中各系列的绝对数值转换为所占的百分比),基线是零,上边界线是 1
// 所以每个堆叠而成的条带长度都一致
// 具体可以参考官方文档 https://github.com/d3/d3-shape/blob/main/README.md#stackOffsetExpand
.offset(d3.stackOffsetExpand)
(d3.index(data, d => d.state, d => d.age)); // group by stack then series key

// Compute the height from the number of stacks.
// 由于不需要将图表的高度限制在一页中,所以基于条形图中条带的数量,通过计算来求出 svg 的高度
const height = series[0].length * 25 + marginTop + marginBottom;

/**
*
* 构建比例尺
*
*/
// 💡 设置横坐标轴的比例尺,与**垂直堆叠条形图**的纵坐标轴相对应
// 横坐标轴的数据是连续型的数值(不同年龄段的人口数量占该州人口总数的比例),使用 d3.scaleLinear 构建一个线性比例尺
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}});
}
Insert cell
// 📝 该 cell 只是用于演示效果
series = d3.stack()
.keys(d3.union(data.map(d => d.age))) // distinct series keys, in input order
.value(([, D], key) => D.get(key).population) // get value for each series key and stack
// 设置堆叠基线函数,这里采用 D3 所提供的一种默认基线函数 d3.stackOffsetExpand
// 对数据进行标准化,基线是零,上边界线是 1(所以每个堆叠而成的条带长度都一致)
// 具体可以参考官方文档 https://github.com/d3/d3-shape/blob/main/README.md#stackOffsetExpand
.offset(d3.stackOffsetExpand)
(d3.index(data, d => d.state, d => d.age)); // group by stack then series key
Insert cell
data = {
const data = await FileAttachment("us-population-state-age.csv").csv({typed: true});
return data.columns.slice(1).flatMap((age) => data.map((d) => ({state: d.name, age, population: d[age]})));
}
Insert cell
import {legend} from "@d3/color-legend"
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