LaTeX 插图与表格
系统讲解 graphicx 插图与 figure 浮动定位、tabular 基础表格列规格、booktabs 学术三线表、multirow/multicolumn/cmidrule 合并单元格以及 table 浮动体与宽表处理。
学完这一章,你能够
- 系统讲解 graphicx 插图与 figure 浮动定位、tabular 基础表格列规格、booktabs 学术三线表、multirow/multicolumn/cmidrule 合并单元格以及 table 浮动体与宽表处理。
插图基础(graphicx)与 figure 浮动体机制
图表是科技论文呈现实验数据与直观结论的核心构件。LaTeX 沿用“内容与版位解耦”的自动化理念:作者只需提供图像或数据并赋予标题与标签,编号、跨页排版和正文引用全部由引擎统筹。插入图片只需两步:导言区加载 `graphicx` 宏包,正文调用 `\includegraphics[选项]{文件名}`(常见尺寸与旋转选项见下表)。文件名建议省略扩展名(如写 `sin` 而非 `sin.png`),XeLaTeX 会按支持优先级自动匹配 PDF、PNG 或 JPG,日后将位图替换为矢量 PDF 无需改动源码。缩放尺寸时应优先使用相对版心比例(如 `width=0.8\textwidth`)而非 `scale`,确保图片永远不会溢出版心边缘。
在正式文档中,图片不应直接硬塞在段落流里,而应包裹进 `figure` 浮动体环境:典型写法为 `\begin{figure}[htbp]`,内部先用 `\centering` 居中,再依次放置 `\includegraphics`、`\caption{图题}` 与 `\label{fig:sin}`(务必把 `\label` 写在 `\caption` 之后才能绑定正确的图编号)。方括号中的 `h/t/b/p/!` 是向排版引擎提供的浮动位置建议(详见浮动参数表)。图片“跑到页面顶部或下一页”并非程序故障,而是浮动算法为避免页面底部留下大片空白作出的优化;若确需把图钉死在源码位置,可加载 `float` 宏包并使用大写 `[H]` 选项。
基础表格(tabular)与学术标准三线表(booktabs)
基础表格由 `tabular` 环境构造,单元格分隔与换行语法与矩阵完全相同——`&` 分列、`\\` 换行,并在环境参数中声明每列对齐方式与竖线规则(例如 `{|l|c|r|}` 表示三列依次左对齐、居中、右对齐且两侧与列间均画竖线,行间用 `\hline` 画横线;`p{2cm}` 则固定列宽并在单元格内自动折行,详见列格式符号表)。
在学术期刊与学位论文出版规范中,标准形式是“三条横线、零条竖线”的三线表,由 `booktabs` 宏包提供支持:列格式写为无竖线的 `{lccc}`,分别用较粗的 `\toprule`(顶线)、较细的 `\midrule`(表头分隔中线)和较粗的 `\bottomrule`(底线)勾勒层次。平时课程作业使用 `|` 与 `\hline` 全边框尚可,但投稿或提交毕业论文前应统一转换为 `booktabs` 三线表,去除冗余竖线以符合专业排印审美。
复杂双层表头:multirow、multicolumn 与 cmidrule
面对分组指标等双层或多层表头时,横向跨列合并直接使用 LaTeX 内置命令 `\multicolumn{列数}{列格式}{内容}`,纵向跨行合并则加载 `multirow` 宏包并调用 `\multirow{行数}{*}{内容}`(在被跨越的下一行对应列位置留空,仅保留 `&` 占位)。搭配 `booktabs` 的局部横线命令 `\cmidrule(lr){2-3}`,即可仅在第 2 至第 3 列下方绘制两端微缩留白 `(lr)` 的精致短横线(三项命令语法详见下表)。
table 浮动体、宽表急救方案与本章小结
为了给表格赋予自动编号、标题、交叉引用与自动分页浮动能力,需将 `tabular` 装入 `table` 浮动体环境(`\begin{table}[htbp] \centering \caption{...} \label{tab:...} ... \end{table}`)。排印界有两条通行惯例:图题置于图片下方,而表题置于表格上方;标签前缀分别采用 `fig:` 与 `tab:`,便于在长文档中一眼区分对象类型。当表格列数过多超出正文版心时,有两种常用急救策略:一是在整个 `tabular` 外套 `\resizebox{\textwidth}{!}{...}` 等比缩放(快捷但会同步缩小表内字号);二是改用 `tabularx` 宏包按可用宽度自动分配列宽(字号一致、更合规范)。文末小结表汇总了本章全部图表核心指令。
\includegraphics 常用图形尺寸与变换选项
| 常用选项 | 含义 | 示例 |
|---|---|---|
| width | 设置图片宽度,推荐相对版心宽度的比例值 | width=0.8\textwidth(版心宽的 80%) |
| height | 显式指定图片高度(未设 width 时保持纵横比) | height=5cm |
| scale | 按原始尺寸倍率缩放 | scale=0.5 |
| angle | 按逆时针角度旋转图片 | angle=90 |
figure / table 浮动体位置建议参数
| 参数 | 含义 | 优先级说明 |
|---|---|---|
| h | here,优先放置在源码所在处 | 仅为建议,若当前页剩余空间不足则顺延 |
| t | top,放置于页面顶部区域 | 学术期刊与双栏论文最常采用 |
| b | bottom,放置于页面底部区域 | 常与 t 组合形成 [htbp] |
| p | float page,归入独立浮动页 | 多图表密集出现时自动集中成页 |
| !(如 [!h]) | 放宽内置浮动比例与数量限制 | 强烈希望就近摆放时叠加使用 |
tabular 基础列格式符号说明
| 列格式符号 | 含义 |
|---|---|
| l / c / r | 该列内容分别左对齐 / 居中对齐 / 右对齐 |
| | | 在对应列边界绘制垂直分隔线(学术三线表禁用) |
| p{2cm} | 指定固定列宽并在单元格内自动换行(顶端对齐) |
复杂表头合并与局部横线命令
| 命令 | 语法 | 说明 |
|---|---|---|
| \multirow | \multirow{行数}{*}{内容} | 纵向合并多行,被跨行的对应单元格留空占位 |
| \multicolumn | \multicolumn{列数}{列格式}{内容} | 横向合并多列,需为合并格重新声明对齐格式 |
| \cmidrule | \cmidrule(lr){2-3} | 在指定起止列绘制部分横线,(lr) 使左右端微缩更精致 |
插图与表格常用命令小结
| 需求 | 命令 / 环境 |
|---|---|
| 插图 | \includegraphics[width=0.8\textwidth]{文件名} |
| 图/表浮动体 | figure / table + [htbp] + \centering + \caption + \label |
| 表格骨架 | tabular,& 分列、\\ 换行 |
| 三线表 | booktabs:\toprule \midrule \bottomrule |
| 合并单元格 | \multirow、\multicolumn |
| 部分横线 | \cmidrule(lr){2-3} |
离线校验 figure 浮动参数、tabular 列规格、booktabs 三线表与双层合并表头
"""Offline LaTeX verification lab for Chapter 08 (latex-figures-tables)."""
import json
import re
VERSION = "CPython 3.12.14 offline LaTeX figure & tabular structure verifier"
def parse_tabular_colspec(spec: str) -> dict:
cols = []
vrules = 0
i = 0
while i < len(spec):
ch = spec[i]
if ch in "lcr":
cols.append(ch)
i += 1
elif ch == "|":
vrules += 1
i += 1
elif ch == "p" and i + 1 < len(spec) and spec[i + 1] == "{":
end = spec.index("}", i + 2)
cols.append(spec[i : end + 1])
i = end + 1
else:
i += 1
return {"columns": cols, "column_count": len(cols), "vertical_rules": vrules}
def case_graphicx_and_figure_float():
doc = r"""
\documentclass{ctexart}
\usepackage{graphicx}
\begin{document}
正弦函数 $y = \sin x$ 的图像如图~\ref{fig:sin} 所示。
\begin{figure}[htbp]
\centering
\includegraphics[width=0.6\textwidth]{sin}
\caption{正弦函数曲线}
\label{fig:sin}
\end{figure}
\end{document}
"""
fig_m = re.search(r"\\begin\{figure\}\[([^\]]+)\](.+?)\\end\{figure\}", doc, re.S)
placement = fig_m.group(1)
body = fig_m.group(2)
inc = re.search(r"\\includegraphics\[([^\]]+)\]\{([^}]+)\}", body)
cap_pos = body.find(r"\caption{")
lbl_pos = body.find(r"\label{")
inc_pos = body.find(r"\includegraphics")
actual = {
"placement_tokens": list(placement),
"valid_standard_floats": all(c in set("htbp!") for c in placement),
"uses_centering": r"\centering" in body,
"image_option": inc.group(1),
"image_name_omits_ext": "." not in inc.group(2),
"caption_below_image_and_before_label": inc_pos < cap_pos < lbl_pos,
"label_prefix": re.search(r"\\label\{([^:]+):", body).group(1),
}
expected = {
"placement_tokens": ["h", "t", "b", "p"],
"valid_standard_floats": True,
"uses_centering": True,
"image_option": r"width=0.6\textwidth",
"image_name_omits_ext": True,
"caption_below_image_and_before_label": True,
"label_prefix": "fig",
}
return {
"name": "graphicx_and_figure_float",
"summary": "检验 figure 浮动位置参数、无扩展名插图、相对版心宽度及“图在下题、先 \\caption 后 \\label”规范",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_basic_tabular_colspec_and_rows():
doc = r"""
\begin{tabular}{|l|c|r|}
\hline
姓名 & 年龄 & 得分 \\
\hline
张三 & 20 & 92 \\
李四 & 21 & 88 \\
\hline
\end{tabular}
"""
m = re.search(r"\\begin\{tabular\}\{([^}]+)\}(.+?)\\end\{tabular\}", doc, re.S)
col_info = parse_tabular_colspec(m.group(1))
data_lines = [ln.strip() for ln in m.group(2).splitlines() if "&" in ln]
row_widths = [len(ln.rstrip("\\ ").split("&")) for ln in data_lines]
p_col_info = parse_tabular_colspec("lp{2cm}r")
actual = {
"col_info": col_info,
"row_count": len(data_lines),
"all_rows_match_cols": all(w == col_info["column_count"] for w in row_widths),
"p_col_parsed": p_col_info["columns"],
}
expected = {
"col_info": {"columns": ["l", "c", "r"], "column_count": 3, "vertical_rules": 4},
"row_count": 3,
"all_rows_match_cols": True,
"p_col_parsed": ["l", "p{2cm}", "r"],
}
return {
"name": "basic_tabular_colspec_and_rows",
"summary": "解析 tabular 列格式(|l|c|r| 与 p{2cm})及数据行列数一致性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_booktabs_three_line_table():
doc = r"""
\documentclass{ctexart}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{lccc}
\toprule
算法 & 准确率 & 召回率 & F1 \\
\midrule
模型 A & 0.91 & 0.88 & 0.89 \\
模型 B & 0.93 & 0.90 & 0.91 \\
\bottomrule
\end{tabular}
\end{document}
"""
spec = re.search(r"\\begin\{tabular\}\{([^}]+)\}", doc).group(1)
col_info = parse_tabular_colspec(spec)
rules = re.findall(r"\\(toprule|midrule|bottomrule)", doc)
actual = {
"has_booktabs": r"\usepackage{booktabs}" in doc,
"zero_vertical_rules": col_info["vertical_rules"] == 0,
"column_count": col_info["column_count"],
"rule_order": rules,
}
expected = {
"has_booktabs": True,
"zero_vertical_rules": True,
"column_count": 4,
"rule_order": ["toprule", "midrule", "bottomrule"],
}
return {
"name": "booktabs_three_line_table",
"summary": "验证 booktabs 学术三线表零竖线原则及 \\toprule -> \\midrule -> \\bottomrule 顺序",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_multirow_multicolumn_and_table_float():
doc = r"""
\usepackage{booktabs}
\usepackage{multirow}
\begin{table}[htbp]
\centering
\caption{实验结果对比}
\label{tab:result}
\begin{tabular}{lcc}
\toprule
\multirow{2}{*}{数据集} & \multicolumn{2}{c}{准确率} \\
\cmidrule(lr){2-3}
& 训练集 & 测试集 \\
\midrule
MNIST & 0.99 & 0.98 \\
CIFAR-10 & 0.95 & 0.91 \\
\bottomrule
\end{tabular}
\end{table}
"""
mr = re.search(r"\\multirow\{(\d+)\}\{([^}]+)\}\{([^}]+)\}", doc)
mc = re.search(r"\\multicolumn\{(\d+)\}\{([^}]+)\}\{([^}]+)\}", doc)
cm = re.search(r"\\cmidrule\(([^)]+)\)\{(\d+-\d+)\}", doc)
cap_pos = doc.find(r"\caption{")
tab_pos = doc.find(r"\begin{tabular}")
# Row 1 effective columns: 1 (from multirow cell) + 2 (from multicolumn{2}) = 3
row1_cols = 1 + int(mc.group(1))
spec_cols = parse_tabular_colspec("lcc")["column_count"]
actual = {
"multirow_span_and_text": [int(mr.group(1)), mr.group(3)],
"multicolumn_span_align_text": [int(mc.group(1)), mc.group(2), mc.group(3)],
"cmidrule_trim_range": [cm.group(1), cm.group(2)],
"header_row1_matches_colspec": row1_cols == spec_cols,
"table_caption_above_tabular": cap_pos < tab_pos,
"label_prefix": re.search(r"\\label\{([^:]+):", doc).group(1),
}
expected = {
"multirow_span_and_text": [2, "数据集"],
"multicolumn_span_align_text": [2, "c", "准确率"],
"cmidrule_trim_range": ["lr", "2-3"],
"header_row1_matches_colspec": True,
"table_caption_above_tabular": True,
"label_prefix": "tab",
}
return {
"name": "multirow_multicolumn_and_table_float",
"summary": "检验 \\multirow/\\multicolumn/\\cmidrule(lr){2-3} 双层表头列宽配平与 table 浮动体表题置顶规范",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_graphicx_and_figure_float(),
case_basic_tabular_colspec_and_rows(),
case_booktabs_three_line_table(),
case_multirow_multicolumn_and_table_float(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在离线脚本中验证 \includegraphics 相对宽度与图题顺序、tabular 列格式解析、booktabs 零竖线三线序以及 \multirow/\multicolumn/\cmidrule 列数配平。
所需环境:Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。
当前源码 SHA256:35d1f45f828c177771d3f239c841ab037c48465eb37add07600766889feba233
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。
ZIP SHA256:e05ec732ba66891be959cf32ad899d3e07c55e3e4db837278e44f090d18d774b
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 `figure` 和 `table` 浮动体中,通常规定图题放在图片下方而表题放在表格上方,且 `\label` 必须写在 `\caption` 之后?
展开参考解答
图题置下、表题置上是中英文科技出版的通用视觉惯例;而 `\caption` 会触发递增图/表计数器并更新当前锚点,若把 `\label` 误放在 `\caption` 之前,`\ref` 引用到的将是外层章节号而非图表编号。