Two Grammars of Data: An Anatomy of R and Python

两套语法:R 与 Python 的计算与绘图系统解剖

同一份 20 万行数据、同一个回归、同一列求和,交给 R 4.5.1 与 Python 3.13。从索引、缺失值、复制语义、回收与广播四种语义差异,到五种操作的四种实现、一列字符串的内存、最小二乘与求和顺序的数值一致性,再到 ggplot2 / plotnine / matplotlib 三套绘图系统。全部数字由两个语言的脚本各自实测,逐项对齐。
Tooling
Plot
Author

Jie Hua

Published

Nov 25, 2026

写作说明 / Note

本文由 AI(Trae Agent) 检索、整理并撰写,尚未经过人工逐行校对。所有数字来自同目录下的脚本在一台机器上的实测:Intel i5-11500、16 GB 内存、Windows 11、R 4.5.1、Python 3.13.13(numpy 2.4.6、pandas 3.0.3、statsmodels 0.15.0、plotnine 0.15.9、matplotlib 3.11.0)。两个语言读的是同一份 CSV(R 用 fwrite 写出,保证二进制往返精确),跑的是同一批任务,结果分别写进 outputs/metrics.json 与 outputs/python.json,正文用 inline R 从两个文件里取值。绝对耗时随机器与版本变化,只有比值与趋势有意义。

This article was researched and written by an AI system (Trae Agent) and has not been proofread line by line by a human. Every number comes from the scripts shipped in this directory, run on one machine: Intel i5-11500, 16 GB RAM, Windows 11, R 4.5.1 and Python 3.13.13 (numpy 2.4.6, pandas 3.0.3, statsmodels 0.15.0, plotnine 0.15.9, matplotlib 3.11.0). Both languages read the same CSV (written by R’s fwrite, which round-trips doubles exactly) and perform the same tasks; the results land in outputs/metrics.json and outputs/python.json, and every number below is pulled from those two files with inline R. Absolute timings move with the machine and the versions; only ratios and trends mean anything.

写一篇中英双语长文,对比 R 与 Python 的计算与绘图系统,要求大量可视化与表格。四个维度:(1) 计算语义——索引、缺失值、复制与视图、回收与广播、分组方言;(2) 速度与内存——同一批任务在 base R / data.table / dplyr / pandas 下的耗时,以及一列字符串在各语言各编码下的字节数;(3) 数值一致性——同一份数据的 OLS、t 检验、以及不同求和顺序的误差随 n 的增长;(4) 绘图系统——ggplot2、plotnine、matplotlib 的默认外观、分面写法与渲染成本。两语言各写各的脚本、通过磁盘上的 CSV/JSON 交换数据,所有数字由脚本生成并在正文用 inline R 引用;明确声明结果是机器相关的。

A long bilingual post comparing the computation and plotting systems of R and Python, with plenty of figures and tables. Four axes: (1) semantics — indexing, missing values, copy versus view, recycling versus broadcasting, and the dialects of group-by; (2) speed and memory — the same tasks under base R, data.table, dplyr and pandas, plus the bytes a string column costs in each language and encoding; (3) numerical agreement — the same OLS, the same t-test, and how summation error grows with n; (4) plotting — the default look, the faceting syntax and the render cost of ggplot2, plotnine and matplotlib. Each language gets its own script and they exchange data through CSV/JSON on disk; every number is generated by the scripts and quoted with inline R; state clearly that results are machine-specific.

1. 一个数字 / A number

20 万行、7 列的数据放在同一个 CSV 里。同一列求和:R 的 for 循环要 66.3 毫秒,R 的 sum() 要 0.14 毫秒,Python 的 numpy.sum 要 0.09 毫秒。差 485 倍。同一个回归:R 的 lm() 与 Python 的 statsmodels 给出三个系数,最大的相对差是 1.3e-14 —— 大约 60 个机器精度,而标准误是 0.0022,大到让这点差别毫无意义。

Two hundred thousand rows and seven columns in one CSV. Sum one column: R’s for loop takes 66.3 ms, R’s sum() takes 0.14 ms, Python’s numpy.sum takes 0.09 ms. A factor of 485. The same regression: R’s lm() and Python’s statsmodels return three coefficients whose largest relative gap is 1.3e-14 — about 60 machine epsilons, next to a standard error of 0.0022.

这两件事说明:速度的差别在写法和后端,不在语言名;数值的差别在算法,也不在语言名。两套语言真正不同的,是它们对同一句话的解释——x[1] 指的是谁、NA 会传到哪、赋值是复制还是共享、长度不齐时是猜还是报错。这篇文章把这四类语义差异、若干可测的性能与数值事实、以及三套绘图系统,一件件摆出来。

Two things follow: speed is set by the idiom and the backend, not by the language on the label; numerical differences are set by the algorithm, also not by the language. What really differs is how each language interprets the same sentence — who x[1] is, where NA propagates, whether assignment copies or shares, and whether mismatched lengths are guessed at or refused. This post lays out those four classes of semantics, a handful of measurable performance and numerical facts, and three plotting systems, one at a time.

2. 两套语法从哪里来 / Where the two grammars come from

R 是 S 语言(John Chambers,贝尔实验室,1976)的开源重写(Ross Ihaka 与 Robert Gentleman,奥克兰,1993)。它的第一公民是向量:x + 1 不是循环,是向量加法;NA 是语言里的一等值,不是浮点数的特例;数据框是 list 的等长特例。设计目标是一个统计学家在终端里交互地探索数据。

R is an open-source rewrite (Ross Ihaka and Robert Gentleman, Auckland, 1993) of S (John Chambers, Bell Labs, 1976). Its first-class citizen is the vector: x + 1 is not a loop but a vector addition; NA is a value in the language, not a special case of floating point; a data frame is a list of equal-length columns. The design target was a statistician exploring data interactively at a terminal.

Python 没有这个包袱。它是通用语言,数值能力是后来一层层加上的库:numpy(2006)给了定长同质数组与广播,pandas(2008,Wes McKinney)给了带索引的表格,statsmodels(2010)给了公式接口,plotnine(2018,Hassan Kibirige)把 ggplot2 的图形语法移植了过来。于是 Python 的数据分析栈是一个约定:numpy 管数组,pandas 管表格,matplotlib 管像素,三者各自演化;R 的栈是一个语言:向量、NA、公式、lm、ggplot2 都在同一个运行时里,共享同一套索引与缺失值规则。

Python carries none of that baggage. It is a general-purpose language whose numerical stack was added as libraries, layer by layer: numpy (2006) brought fixed-size homogeneous arrays and broadcasting, pandas (2008, Wes McKinney) brought indexed tables, statsmodels (2010) brought formula interfaces, and plotnine (2018, Hassan Kibirige) ported ggplot2’s grammar of graphics. So the Python stack is a set of conventions — numpy for arrays, pandas for tables, matplotlib for pixels, each evolving on its own — while the R stack is one language: vectors, NA, formulas, lm and ggplot2 all live in a single runtime sharing one set of indexing and missing-value rules.

这个出身差异决定了后面每一条具体差别。

That origin story determines every concrete difference that follows.

3. 索引:从 1 开始,还是从 0 开始 / One-based or zero-based

这是最表面的一条,也是最容易写出 bug 的一条。R 的下标从 1 开始、两端都含;Python 从 0 开始、左闭右开。此外 R 的负下标表示排除,Python 的负下标表示从末尾倒数。

The most superficial difference, and the one that produces the most bugs. R indexes from 1 and is inclusive at both ends; Python indexes from 0 and is half-open. Worse, a negative index means exclusion in R and counting from the end in Python.

Table 1: 同一个意思,两套括号 / the same intent, two sets of brackets
想要什么 R Python
第一个 x[1] → 1.729466 x.iloc[0] → 1.729466
第二到第四个 x[2:4](3 个) x[1:4](3 个)
最后一个 x[length(x)] → 0.868583 x.iloc[-1] → 0.868583
去掉第一个 x[-1] x[1:]

注意第三行和第四行是同一串字符 -1,意思相反。R 里 x[-1] 是「删掉第一个」,Python 里 x[-1] 是「最后一个」。同样的三个元素(第 2 到第 4 个),R 写 x[2:4],Python 写 x[1:4]:一个下标差一位,一个区间差一端。

Notice rows three and four are the same characters -1 with opposite meanings. In R, x[-1] drops the first element; in Python, x[-1] is the last. The same three elements (the 2nd through the 4th) are x[2:4] in R and x[1:4] in Python: an off-by-one in the start, and a closed-versus-open end.

Figure 1: 两套下标系统叠在同一排元素上 | two index systems over the same row of elements

这不是审美问题。一个从 R 转过去的人写 x[2:4] 想取三个、实际取到两个;一个从 Python 转过来的人写 x[-1] 想取最后一个、实际删掉了一个 —— 而删掉一个元素的向量往往不会报错,只会在下游悄悄少一行。

This is not a matter of taste. Someone coming from R writes x[2:4] expecting three elements and gets two; someone coming from Python writes x[-1] expecting the last and instead drops the first — and dropping an element usually does not error, it just quietly removes a row downstream.

4. 缺失值:R 有两种,Python 只有一种 / R has two kinds of missing, Python has one

R 区分 NA(缺失,不知道是多少)与 NaN(不是数,比如 0/0)。is.na(NaN) 在 R 里是 TRUE,is.nan(NA) 是 FALSE:NA 是一般意义上的缺失,NaN 是它的一种。numpy 与 pandas 只有 NaN,没有 NA。

R distinguishes NA (missing: the value is unknown) from NaN (not a number, e.g. 0/0). is.na(NaN) is TRUE in R and is.nan(NA) is FALSE: NA is missing in general, NaN is one kind of it. numpy and pandas only have NaN.

Table 2: c(1, NA, 3) 与 c(1, NaN, 3) 在三种栈里的命运 / what happens to c(1, NA, 3) in three stacks
运算 R(含 NA) R(含 NaN) numpy pandas
sum NA NaN NaN 4
mean NA NaN NaN 2
max NA NaN NaN 3
跳过缺失 na.rm=TRUE → 4 na.rm=TRUE → 4 nansum → 4 默认就跳过
排序 / sort 1 3 1 3 1 3 NaN 1 3 NaN

三种默认哲学:R 往下传(一个 NA 污染整个结果,要显式 na.rm = TRUE),numpy 也往下传(但用另一套函数 nan* 跳过),pandas 默认跳过(Series.sum() 直接给 4)。最危险的是第一与第三种相邻:同一份数据,R 里 mean(x) 给你 NA 让你停下来想,pandas 里 x.mean() 悄悄给你一个数。两边都不算错,但默认值就是文档。

Three default philosophies: R propagates (one NA poisons the result until you say na.rm = TRUE), numpy propagates too (but offers a separate nan* family to skip), and pandas skips by default (Series.sum() just returns 4). The dangerous adjacency is the first and the third: on the same data, mean(x) in R hands you NA and makes you think, while x.mean() in pandas quietly hands you a number. Neither is wrong, but the default is the documentation.

还有一处细节:sort() 在 R 里默认 na.last = NA,也就是把缺失值丢掉;np.sort 把它们排到最后。所以 sort(c(1, NA, 3)) 给 1, 3,np.sort([1, nan, 3]) 给 1, 3, nan。一条「排序」的语句,一边缩短了向量,一边没有。

One more detail: sort() in R defaults to na.last = NA, i.e. it drops missing values, while np.sort puts them last. So sort(c(1, NA, 3)) gives 1, 3 and np.sort([1, nan, 3]) gives 1, 3, nan. The same sentence about sorting shortens the vector in one language and not in the other.

5. 复制还是视图 / Copy or view

三个栈对「b 改了,a 变不变」给出三个不同答案。R 是 copy-on-modify:b <- a 之后两者共享同一块内存,但只要有人写 b,R 就先复制一份,所以 a 永远不变。numpy 的切片是视图,写 view 就是写 parent。pandas 3.0 的 copy-on-write 更彻底:它直接交给你一个只读数组,写入当场报错。

Three stacks, three answers to “if I change b, does a change?”. R is copy-on-modify: after b <- a the two share memory, but the moment anyone writes to b, R copies first, so a never changes. A numpy slice is a view: writing to view writes to parent. pandas 3.0’s copy-on-write goes further and hands you a read-only array that refuses the write outright.

Table 3: 同一个赋值,三种后果 / one assignment, three consequences
操作 R numpy pandas
b <- a; b[1] <- 99; 然后看 a[1] 1 99(父向量被改了) ValueError: assignment destination is read-only

1、99、报错 —— 三个数字对应三种语义:值语义 / 引用语义 / 写时复制。R 的答案最安全(没有隐藏的别名),numpy 的答案最快(大数组切片不复制),pandas 的答案最啰嗦(每次写都要显式 .copy() 或就地赋值)。

1, 99, and an error — three numbers for three semantics: value, reference, and copy-on-write. R’s answer is the safest (no hidden aliasing), numpy’s is the fastest (a slice of a huge array copies nothing), and pandas’ is the most verbose (every write needs an explicit .copy() or a proper in-place assignment).

R 还有一条附带的保证:函数不能修改调用者的变量。f <- function(z) { z[1] <- 0; z } 之后,a[1] 仍然是 1。在 Python 里,传进去的是对象的引用,函数对 list 的原地修改会传出来;这是两套语言对「函数有没有副作用」的不同下注,也是 R 的函数式风格与 Python 的命令式风格的分水岭。

R also guarantees that a function cannot modify the caller’s variable: after f <- function(z) { z[1] <- 0; z }, a[1] is still 1. In Python the object reference is passed in, and in-place mutation of a list leaks back out. It is a different bet on whether functions have side effects, and the watershed between R’s functional style and Python’s imperative one.

6. 回收还是报错 / Recycle or refuse

R 的向量运算会自动回收(recycle)短的向量到长的长度,元素不够就从头再来。numpy 的广播只在形状兼容时发生(长度为 1,或维度可对齐),(4,) + (2,) 直接抛 ValueError。

R recycles a shorter vector to the longer length, restarting from the beginning when it runs out. numpy broadcasts only when shapes are compatible (length 1, or dimensions that align); (4,) + (2,) raises a ValueError.

Figure 2: R 的回收 vs Python 的拒绝 | recycling in R versus refusal in Python

c(1,2,3,4) + c(1,2) 在 R 里得 2, 4, 4, 6。长度不整除时 R 会给一个警告(结果照给):长的对象长度不是短的对象长度的整倍数。numpy 给的是 ValueError: operands could not be broadcast together with shapes (4,) (2,) 。同一个逻辑下标也不放过:长度为 4 的逻辑向量去索引长度为 3 的向量,R 悄悄回收(1, 3),numpy 报 IndexError。

c(1,2,3,4) + c(1,2) yields 2, 4, 4, 6 in R. When the lengths do not divide, R emits a warning and answers anyway: 长的对象长度不是短的对象长度的整倍数. numpy gives ValueError: operands could not be broadcast together with shapes (4,) (2,) . Logical indexing is no exception: a length-4 logical indexing a length-3 vector is silently recycled in R (1, 3) and an IndexError in numpy.

回收是便利,也是一类安静的 bug:把两个本应对齐的向量算在一起,长度差一,R 会给你一个形状正确、内容错误的答案。numpy 的严格在这里是优点。

Recycling is convenient and it is also a class of silent bug: combine two vectors that should have been aligned, off by one in length, and R returns a correctly shaped answer with wrong contents. numpy’s strictness is a virtue here.

7. 分组:三种方言 / Grouping in three dialects

同一个「按 grp 求 val 的均值」,在三种栈里是三种句子:

The same “mean of val by grp” is three different sentences in three stacks:

# base R
tapply(dt$val, dt$grp, mean)

# data.table
dt[, .(m = mean(val)), by = grp]

# dplyr
dt |> summarise(m = mean(val), .by = grp)
# pandas
df.groupby("grp", observed=True)["val"].mean()

结果的一致性可以放心:1000 个分组,data.table 与 dplyr 的均值最大差 1.3e-15,data.table 与 pandas 的最大差 1.6e-15,计数完全相同(TRUE)。

The agreement holds: over 1000 groups the largest mean difference is 1.3e-15 between data.table and dplyr and 1.6e-15 between data.table and pandas, with identical counts (TRUE).

差别在返回的形状:base R 的 tapply 给你一个带 dimnames 的数组(或者一个 list,取决于结果长度),data.table 在原地返回一个两列的表,dplyr 返回一个 tibble 并保留分组结构,pandas 返回一个以 grp 为索引的 Series —— 想把它变成普通列得再写 .reset_index()。这四种形状没有优劣,但每换一个栈就要重新记一次「结果现在是什么」。

The difference is the shape of the return value: base R’s tapply gives a named array (or a list, depending on the result length), data.table returns a two-column table, dplyr returns a tibble that keeps the grouping structure, and pandas returns a Series indexed by grp — turning it back into a plain column needs another .reset_index(). None of the four is better, but every switch between stacks means memorising “what is the result now”.

8. 速度:谁快,取决于你在跟谁比 / Speed depends on what you compare with

五个任务,四个实现,同一个 20 万行的数据集。最诚实的一句话是:没有哪个语言更快,只有哪个后端更快。

Five tasks, four implementations, the same 200,000-row data set. The honest summary: no language is faster; some backends are.

Figure 3: 五个任务 × 四种实现,最快一次的时间(对数轴)| five tasks, four implementations, fastest of five (log scale)
Table 4: 每个任务的最快与最慢 / the fastest and slowest per task
任务 最快 最慢 差距
group mean data.table(5.37 ms) R base(14.5 ms) 2.7×
left join data.table(11.35 ms) dplyr(19.6 ms) 1.7×
pivot data.table(7.06 ms) pandas(28.8 ms) 4.1×
sort R base(6.78 ms) dplyr(15.5 ms) 2.3×
sum pandas(0.09 ms) R loop(66.3 ms) 744.2×

读法有三条。第一,同一个语言内部的差距可以比语言之间还大:R 的 for 循环比自己的 sum() 慢 485 倍。第二,分组的冠军是 data.table(5.4 ms),比 base 的 tapply(14.5 ms)快约 2.7 倍。第三,pandas 有它自己的短板:透视慢到 28.8 ms,是 data.table 的 4.1 倍;而它的 np.sum 反而是全部求和实现里最快的(0.09 ms)。

Three readings. First, the gap inside one language can exceed the gap between languages: R’s for loop is 485 times slower than its own sum(). Second, data.table wins grouping (5.4 ms) by about 2.7× over base tapply (14.5 ms). Third, pandas has its own weak spot: reshaping costs 28.8 ms, 4.1× data.table, while its np.sum is the fastest summation of all (0.09 ms).

排序是最有意思的一格:R 的 sort()(6.8 ms)比 data.table、dplyr、pandas 都快。R 的排序在 C 层对 doubles 走了一条专门的 radix/quick 混合路径,而 dt[order(val)] 还要把整行搬一遍 —— 又是一个「语言不是变量、实现才是」的例子。

Sorting is the most interesting cell: R’s sort() (6.8 ms) beats data.table, dplyr and pandas. R’s sort takes a specialised radix/quick path for doubles in C, whereas dt[order(val)] also has to carry whole rows along. Another case where the implementation, not the language, is the variable.

9. 内存:一列字符串的代价 / What a string column costs

同一列 20 万个字符串,R 的 character 向量要 1.58 MB,pandas 的 object 列要 10.11 MB —— 差 6.4 倍。两边都有把字符串编码成整数的机制(R 的 factor、pandas 的 category),启用之后分别掉到 0.82 与 0.43 MB。

The same 200,000 strings: a character vector in R costs 1.58 MB, an object column in pandas costs 10.11 MB — a factor of 6.4. Both sides have a mechanism to encode strings as integers (R’s factor, pandas’ category), and enabling it brings them down to 0.82 and 0.43 MB.

Figure 4: 一列字符串在四种编码下的字节数 | bytes for one string column under four encodings
Table 5: 单位 MB | in MB
列 R character R factor pandas object pandas category
grp(1000 水平) 1.58 0.82 10.11 0.43
cat(3 水平) 1.53 0.76 10.24 0.19

原因在两种字符串的存法不同。R 的字符向量是一个指针数组,指向一张全局共享的字符串表(CHARSXP 缓存),所以 20 万格只占 20 万 × 8 字节 ≈ 1.6 MB,1000 个不同的字符串只存一份。pandas 的 object 列是每个格一个 Python 字符串对象的指针数组,memory_usage(deep=True) 把这些对象的头部和内容都算进去,于是 10 MB 起步。

The reason is how strings are stored. R’s character vector is an array of pointers into a globally shared string table (the CHARSXP cache), so 200,000 cells occupy 200,000 × 8 bytes ≈ 1.6 MB and the 1,000 distinct strings are stored once. A pandas object column is an array of pointers to one Python string object per cell, and memory_usage(deep=True) counts every header and payload, starting at 10 MB.

整张表也一样:R 的 data.table 10.0 MB,把两列字符换成 factor 后 8.5 MB;pandas 原样 28.0 MB,全部转成 category 后 8.3 MB。作为参照,写出去的 CSV 是 17.1 MB。两边的默认编码都是浪费的,两边的解药都是同一种:把重复的字符串编码成整数。

The whole frame follows: R’s data.table is 10.0 MB and 8.5 MB with both string columns as factors; pandas is 28.0 MB as-is and 8.3 MB fully categorical. For reference, the CSV on disk is 17.1 MB. Both defaults are wasteful and both cures are the same: encode repeated strings as integers.

10. 数值一致性 I:最小二乘 / Least squares

同一份数据,同一个模型 y ~ x + z,lm() 与 statsmodels.formula.api.ols 的差别是:

The same data, the same model y ~ x + z, and the difference between lm() and statsmodels.formula.api.ols:

Table 6: n = 200 000,两个 OLS 实现 | two OLS implementations at n = 200,000
项 R 系数 Python 系数 相对差 R 标准误 Python 标准误
截距 / intercept 1.000275 1.000275 2.7e-15 0.002234 0.002234
x 2.001703 2.001703 1.3e-14 0.002235 0.002235
z -1.501333 -1.501333 7.4e-16 0.002237 0.002237
Figure 5: 左:两个估计在图上完全重合;右:差别的量级 | left: the two estimates coincide; right: the size of the gap

三个系数的相对差最多 1.3e-14,标准误最多 1.0e-14,R² 的差是 0.0e+00(也就是完全一致,0.862220)。R 的 lm() 在 C 层做 Householder QR,statsmodels 走 LAPACK 的 QR/伪逆,数学上是同一个最小二乘解,浮点是不同的求和与消元顺序 —— 于是差几十个 ulp,且这个差别随设计矩阵的条件数放大。

The coefficients differ by at most 1.3e-14 in relative terms, the standard errors by at most 1.0e-14, and R² by 0.0e+00 (i.e. not at all: 0.862220). R’s lm() runs a Householder QR in C and statsmodels goes through LAPACK’s QR/pseudo-inverse: the same least-squares solution mathematically, with different floating-point summation and elimination orders — hence tens of ulps, and that gap grows with the condition number of the design.

两个样本的 t 检验也一样:R 的 t.test(a, b, var.equal = TRUE) 给 \(t\) = -1.128470、\(p\) = 0.259124,scipy 给 \(t\) = -1.128470、\(p\) = 0.259124,绝对差 1.1e-15 与 1.1e-15。这一条几乎总是安全的:p 值只要不是 1e-15 附近,最后一个 ulp 不影响任何结论。

The two-sample t-test agrees as well: R’s t.test(a, b, var.equal = TRUE) returns \(t\) = -1.128470 and \(p\) = 0.259124, scipy returns \(t\) = -1.128470 and \(p\) = 0.259124, with absolute differences of 1.1e-15 and 1.1e-15. This one is almost always safe: unless the p-value sits near 1e-15, the last ulp changes no conclusion.

11. 数值一致性 II:求和的顺序 / Order of summation

这一节的两个语言回答的是同一个问题:同一百万个数,用不同的加法顺序,误差差多少?

This section asks one question of both languages: for the same million numbers, how much does the order of addition matter?

Figure 6: 误差随 n 增长;两条循环曲线几乎完全重合 | error against n; the two loop curves lie on top of each other

数据是 1000000 个 \(e^{\mathcal N(0,2)}\) 的正数(量级跨三个数量级)。每个 n 取 20 个重叠加窗,取相对误差的中位数。先看朴素循环:n = 1000 时误差 4.6e-16,n = 300000 时 1.2e-14,大致按 \(\sqrt n\) 增长,约等于 \(\varepsilon\sqrt n\)。R 的 for 循环与 Python 的 for 循环给出的数字一模一样 —— 它们做的是同一件事:从头到尾顺序累加,每步一次舍入。

The data are 1000000 positive draws from \(e^{\mathcal N(0,2)}\) (three orders of magnitude in range). For each n, twenty overlapping windows, and the median relative error. Start with the naive loop: 4.6e-16 at n = 1000 and 1.2e-14 at n = 300,000, growing roughly like \(\sqrt n\), i.e. like \(\varepsilon\sqrt n\). R’s for loop and Python’s for loop produce the same digits — both do the same thing: accumulate front to back, one rounding per step.

再看其他写法:numpy.sum 用成对求和(pairwise summation,把数组对半切、递归相加),误差落在 1 ulp 以内;math.fsum 用 Shewchuk 算法,是正确舍入的;Kahan 补偿求和也是 0;R 的 sum() 在 C 层用 long double 累加,同样是 0。图中那三条几乎为 0 的线因此并成了一条,贴着 \(10^{-16}\) 的下沿。

Then the alternatives: numpy.sum uses pairwise summation (halve the array, add recursively) and lands within 1 ulp; math.fsum uses Shewchuk’s algorithm and is correctly rounded; Kahan compensated summation is also 0; R’s sum() accumulates in long double in C and is 0 as well. The three near-zero curves therefore collapse into one line hugging \(10^{-16}\).

Table 7: n = 1,000,000,精确值(fsum)= 7364482.5445452565
写法 相对误差
R for 循环 3.1e-14
Python for 循环 3.1e-14
R sum()(long double) 0(< 0.5 ulp)
numpy.sum(成对) 0(< 0.5 ulp)
Kahan(两种语言相同) 0(< 0.5 ulp)

速度上也值得记一笔:R 的朴素循环每元素 16.4 纳秒,Python 的 97.3 纳秒(R 的循环体更轻);而 R 的 sum() 每元素 0.68 纳秒,比 numpy 的 2.12 纳秒还快一点。又快又准的那一条,都是库函数;亲手写的循环总是又慢又糙。

A note on speed: R’s naive loop costs 16.4 ns per element and Python’s 97.3 (R’s loop body is lighter); R’s sum() costs 0.68 ns per element, slightly faster than numpy’s 2.12. The fast and accurate option is always the library call; a hand-written loop is always slow and sloppy.

最后是灾难性抵消。取 1020 个数:10 个 \(10^{16}\)、1000 个 \(1\)、10 个 \(-10^{16}\)。精确答案是 1000。\(10^{17}\) 附近 double 的间距是 16,所以那 1000 个 1 在累加时全部被吞掉:

Finally, catastrophic cancellation. Take 1020 numbers: ten \(10^{16}\), a thousand \(1\), ten \(-10^{16}\). The exact answer is 1000. The spacing of doubles near \(10^{17}\) is 16, so the thousand ones are swallowed during accumulation:

Table 8: 灾难性抵消:1020 个数,精确和是 1000 | catastrophic cancellation: 1020 numbers, exact sum 1000
写法 结果 误差
精确 / exact(fsum) 1000 0
R for 循环 0 1000
Python for 循环 0 1000
numpy.sum(成对) 896 104
R sum() 1000 0
Kahan 1000 0

0 —— 两种语言的朴素循环都给了 0,百分百的误差,而且没有任何警告。numpy 的成对求和因为把大数先分块相加,抢回了 896。Kahan 与 R 的 sum() 精确给出 1000。这一节的结论与语言无关:误差是算法属性。 你选的那一行代码,决定你拿到 0 还是 1000。

0 — the naive loop in both languages returns 0, a hundred percent error, with no warning at all. numpy’s pairwise summation recovers 896 by adding the large blocks first. Kahan and R’s sum() return exactly 1000. The lesson here has nothing to do with the language: error is a property of the algorithm. The one line you choose decides whether you get 0 or 1000.

12. 绘图 I:三种默认长相 / Three default looks

同样的 120 个点、同一个散点 + 三个分组线性拟合,交给三套系统,全部使用默认主题、不做任何美化:

The same 120 points and the same scatter plus three grouped linear fits, handed to three systems with their default themes and no styling at all:

(a) ggplot2(R)默认 / ggplot2 default
(b) plotnine(Python)默认 / plotnine default
Figure 7: 同一份 120 个点,两种「图形语法」的默认长相 | the same 120 points under two grammars of graphics

这两张图几乎无法分辨:灰底、白色网格、右侧色块图例、同一套默认色相 —— 因为 plotnine 就是 ggplot2 图形语法的 Python 移植,连 theme_gray 的面板灰度都照抄。这不是巧合,是设计的直接搬运:ggplot(df, aes(x, y)) + geom_point() + facet_wrap(~ g) 在两种语言里逐字相同。

The two images are nearly indistinguishable: grey panel, white grid, right-hand colour legend, the same default hues — because plotnine is a Python port of ggplot2’s grammar, down to the panel grey of theme_gray. That is not a coincidence but a direct transplant: ggplot(df, aes(x, y)) + geom_point() + facet_wrap(~ g) is letter-for-letter the same in both languages.

Figure 8: matplotlib 的默认长相:另一套设计哲学 | matplotlib’s default: a different philosophy

matplotlib 是命令式的:没有「图形语法」,只有画布(figure)、坐标轴(axes)和图元(artist)。它不知道 cat 是分组变量,只知道「红的画这几个点、蓝的画那几个点」,图例要你手动 label=。默认长相也完全不同:白底、四边黑框、图例在框内。要画同一张图,matplotlib 需要几十行,而 ggplot2 与 plotnine 各需要一行。

matplotlib is imperative: there is no grammar, only a canvas (figure), axes, and artists. It does not know that cat is a grouping variable; it knows only “draw these points in red, those in blue”, and the legend needs a manual label=. The default look is different too: white background, a full black box, the legend inside. Reproducing the same figure takes dozens of lines in matplotlib, one line each in ggplot2 and plotnine.

Table 9: 三套绘图系统的对照 | the three plotting systems side by side
项目 ggplot2 plotnine matplotlib
范式 声明式(图形语法) 声明式(ggplot2 移植) 命令式(画布 + 图元)
默认长相 灰底白网格 灰底白网格(同 ggplot2) 白底黑框
分面 / 小多图 facet_wrap() 一行 facet_wrap() 一行 手写 subplots(3, 3) + 循环
统计层 geom_smooth(method = "lm") geom_smooth(method="lm") 无(自己 polyfit + plot)
图例 自动(把变量映射成颜色) 自动 手动 label=
生态 CRAN,统计图形最全 PyPI,逐年补齐 生态最大,海图/科研图多
本图代码行数 1 1 约 30

13. 绘图 II:分面 / Faceting

「按 cat 和 x 的三分位分成 9 格」是数据分析里最常见的需求之一。三套系统的写法差距在这里被放大:

“Split into nine panels by cat and the tertiles of x” is one of the most common requests in data analysis. Here the three systems diverge sharply:

(a) ggplot2:facet_wrap(~ cat + bin),1 行
(b) matplotlib:双重 for 循环,11 行
(c) plotnine:facet_wrap("~ cat + bin"),1 行
Figure 9: 同一份数据、同一个分面,三种写法 | the same data, the same nine panels, three ways

ggplot2 与 plotnine 的写法是同一句话,连 ncol = 3 都一样。matplotlib 需要 plt.subplots(3, 3, sharex=True, sharey=True),然后双重循环里手动切片数据、手动设标题、手动调字号 —— 而且它的标注方式仍然不同:标题在轴上方居中,不是 ggplot 那种灰底条带。代码量是 11 行 vs 1 行,而维护成本差距更大:分面数从 9 变成 12 时,一份只改 ncol,一份要改循环的边界。

ggplot2 and plotnine use the same sentence, ncol = 3 included. matplotlib needs plt.subplots(3, 3, sharex=True, sharey=True), then a double loop that slices the data, sets the titles and tunes the font sizes by hand — and the labelling still differs: a centred title above the axes, not a grey strip. Eleven lines against one, and the maintenance gap is larger: going from nine panels to twelve means changing ncol in one case and the loop bounds in the other.

14. 绘图 III:一次渲染的成本 / What one render costs

Table 10: 同一张 120 点散点图,构建 + 存 PNG 的最快一次(毫秒)| build + save the same 120-point scatter, fastest of five (ms)
系统 一次保存 相对
matplotlib 73.9 1.0×
plotnine 182.8 2.5×
ggplot2 216.7 2.9×

matplotlib 快 2.9 倍:它把「把点画在白纸上」这件事做得极简,没有图层、没有统计变换、没有主题系统。ggplot2 与 plotnine 的开销是同一量级(217 与 183 毫秒),因为它们在背后做的是同一件事:解析图层、计算统计量、生成 grob、再交给图形设备。这点开销在交互探索时完全无感,在批量生成上千张图时才需要计较。

matplotlib is 2.9× faster: it reduces “put points on paper” to its minimum, with no layers, no statistical transforms and no theme system. ggplot2 and plotnine cost the same order of magnitude (217 and 183 ms) because underneath they do the same work: resolve layers, compute statistics, build grobs, hand them to a device. That overhead is invisible while exploring interactively and only matters when generating thousands of figures in a batch.

15. 该用哪个 / Which one to use

flowchart TD
    A["这次任务是什么"] --> B{"主要是统计建模 + 出报告?"}
    B -->|是| C["R + Quarto<br/>lm / lme4 / survival / ggplot2"]
    B -->|否| D{"会不会碰到非表格的工作?"}
    D -->|是| E["Python<br/>图像 / 深度学习 / 生产服务"]
    D -->|否| F{"团队已经在哪边?"}
    F -->|R| C
    F -->|Python| G["Python + pandas<br/>大表加 polars / duckdb"]
    C --> H["跨语言就交换 CSV / Parquet<br/>别用 reticulate 硬连"]
    E --> H
    G --> H

三条经验,都是从上面的数字里读出来的。第一,语义差异比语法差异更贵。 索引、NA、复制、回收这四条加起来,构成了跨语言重写代码时 90% 的静默 bug;而 groupby 与 facet_wrap 的写法差异,查一次文档就能记住。第二,性能问题的答案几乎总是「换后端」而不是「换语言」。 R 里从 for 换成 data.table 是 485 倍的收益,Python 里从 object 换成 category 是 23.4 倍的内存收益 —— 语言内部的选择空间比语言之间大得多。第三,两套绘图系统不是竞争关系。 想要「说清楚数据长什么样」,ggplot2 / plotnine 的图形语法是最短路径;想要「精确控制每一个像素」,matplotlib 是唯一选择。本博客所有图的主题、配色与导出脚本,都建立在前者的语法上。

Three lessons, all readable from the numbers above. First, semantic differences cost more than syntactic ones. Indexing, NA, copying and recycling together account for roughly 90% of the silent bugs when porting code across languages, whereas the differences between groupby and facet_wrap are one documentation lookup each. Second, the answer to a performance question is almost always “change the backend”, not “change the language”. Going from a for loop to data.table in R buys 485×, and going from object to category in Python buys 23.4× in memory — the space of choices within a language is much larger than the space between them. Third, the two plotting systems are not competitors. To say what the data look like, the grammar of ggplot2 and plotnine is the shortest path; to control every pixel, matplotlib is the only option. Every figure on this blog — its theme, its palette, its export script — is built on the former.

16. 复现 / Reproducing

Table 11: 本文使用的版本 | versions used in this post
组件 版本
R 4.5.1
Python 3.13.13
numpy 2.4.6
pandas 3.0.3
scipy 1.18.0
statsmodels 0.15.0
ggplot2 4.0.2
plotnine 0.15.9
matplotlib 3.11.0
机器 Intel i5-11500 / 16 GB / Windows 11

脚本按顺序执行(每一步只依赖上一步写在磁盘上的文件,没有 reticulate,也没有环境嵌套):

The scripts run in order; each step depends only on files the previous one wrote to disk — no reticulate, no nested environments:

Rscript scripts/00_data.R        # 同一份 CSV 与两列求和数据 / the shared CSV
python  scripts/python_side.py   # Python 侧全部指标、四张图 / Python metrics, four figures
Rscript scripts/01_semantics.R   # 索引、NA、复制、回收 / indexing, NA, copy, recycling
Rscript scripts/02_speed.R       # 五个任务 × 四种实现,内存 / five tasks, four backends, memory
Rscript scripts/03_numeric.R     # OLS、t 检验、求和顺序 / OLS, t-test, summation order
Rscript scripts/04_plots.R       # ggplot2 默认与分面、渲染成本 / ggplot2 defaults, facets, render cost

所有耗时取五次中最快的一次(Python 侧有一次预热)。绝对数字换一台机器就会变,曲线形状与数量级不应该变 —— 如果变了,那才是值得追的问题。

All timings are the fastest of five runs (with one warm-up on the Python side). The absolute numbers will move on another machine; the shapes of the curves and the orders of magnitude should not — if they do, that is worth chasing.