第 4 章 · 第 1 节Chapter 4 · Section 1 基础Core
4.1 宽表与长表Wide and long data
区分宽表与长表,追踪同一指标在转换前后的位置。Distinguish wide and long data and trace a measure through reshaping.
本节要点Key points
- 宽表一行一个对象、多列指标;长表一行一个观测。Wide data has one object per row with several measure columns; long data has one observation per row.
- 转换只改变组织方式,数值应保持不变。Reshaping changes organization only; values should remain unchanged.
- 选宽表还是长表取决于后续过滤、分组和绑定。Choose wide or long form based on later filtering, grouping and binding.
01理解概念Understand the concept
案例
原 5.1 节用了 1985 美国 50 州犯罪数据(CSV),含 8 个犯罪指标列。
概念与方法
- 长格式(long):每行一个观测,列 = 字段(如
{state, metric, value})。优点:方便过滤、分组、绑定到 d3 join。 - 宽格式(wide):每行一个实体,列 = 指标(如
{state, murder, robbery, ...})。优点:人眼读得懂、直观。 - 转换:
flatMap+ 循环键名 = 几行代码搞定。 - d3.autoType:自动推断列类型(数字、日期、布尔),省得手动
+d.field。
Case study
Section 5.1 used 1985 U.S. crime data (CSV) for the 50 states, with 8 crime-indicator columns.
Theory
- Long format (long): one observation per row, columns = fields (e.g.,
{state, metric, value}). Pros: easy to filter, group, and bind to a d3 join. - Wide format (wide): one entity per row, columns = metrics (e.g.,
{state, murder, robbery, ...}). Pros: human-readable and intuitive. - Conversion:
flatMap+ iterating over key names = a few lines of code. - d3.autoType: auto-infers column types (number, date, boolean), saving you from manual
+d.field.
02动手实验Try the experiment
试一试:Try this: 对照两种数据结构,找到同一个州的三个指标,检查数值是否保持不变。Find one state’s three measures in both structures and check that values are unchanged.
实验将在进入此区域时加载,需要启用 JavaScript。The experiment loads when you reach this area. JavaScript is required.
Some experiment controls use Chinese labels.
做完后:你应该看到After the experiment: what to look for
03代码与讲解Code and explanation收起 / 展开Collapse / expand +
⭐ 关键代码
⭐ 关键点 1:d3.csv 第二参 = 类型转换回调
// 自动类型推断(数字/日期/布尔)
const raw = await d3.csv('./data/crime.csv', d3.autoType);
console.log(raw[0]); // {state: 'Alabama', population: 3979000, murder: 350, ...}
⭐ d3.autoType 内部就是遍历每列、用 Number() / Date() / 字符串检测。能识别的就转、识别不了保持字符串。
⭐ 关键点 2:宽 → 长(flatMap 模式)
// flatMap:每行展开成多个观测
const long = raw.flatMap(d =>
['murder', 'robbery', 'burglary'].map(key => ({
state: d.state,
metric: key,
value: d[key]
}))
);
// 现在可以做:d3.group(long, d => d.metric)
⭐ flatMap 是 ES2019,是 "map + 一维 flatten" 的简写。比 map().flat() 链式更直观。
★ Key Code
★ Key Point 1: the second argument of d3.csv = the type-conversion callback
const raw = await d3.csv('./data/crime.csv', d3.autoType);
console.log(raw[0]); // {state: 'Alabama', population: 3979000, murder: 350, ...}
★ d3.autoType internally walks each column using Number() / Date() / string detection. Recognized types are converted; unrecognized values stay as strings.
★ Key Point 2: wide → long (the flatMap pattern)
const long = raw.flatMap(d =>
['murder', 'robbery', 'burglary'].map(key => ({
state: d.state,
metric: key,
value: d[key]
}))
);
★ flatMap is ES2019, shorthand for “map + one-level flatten”. More intuitive than the map().flat() chain.
04练习Quiz
学完后,可以标记进度。Mark this section when you finish.