SuperAPI AI Directory

tikz-figure-code

Coding & development

View repository

Updated 10-15 10:19

About this skill

TikZ Figure Code — The engineering fundamentals for writing it right + edit safety

This is thedeterministic foundation: how to write TikZ code that compiles cleanly, doesn't overlap, and doesn't break when you change one thing. Itdoes notgovern "what figure to draw to be beautiful"—that's the design/composition layer's job (see thesis-figure-skill). What this skill governs is: no matter what you draw, the code itself must bewritten correctly and survive editing。

One-sentence positioning: thesis-figure-skill decideswhat to draw, this skill guaranteeshow to write it without errors。

Why it's needed (the root of the problem)

The model's default habit when writing TikZ is **"coordinates by feel"——\node at (5.2, 3.1)、\fill rectangle (x0,y0)(x1,y1), placing them by hand one cell at a time. This isamateur style**, leading to two inevitable kinds of pain:

  1. Writing blind: when you're at line 800 you don't know what it will render as; collisions/overflow/arrows not touching the box can only be discovered after compiling and looking at the figure → you're forced into an expensive "render → review → fix" loop.
  2. Editing breaks it: the same spacing/center is hand-copied in multiple places (zone boundaries, content centers, arrow coordinates, bottom bar…). Changing one stage's width requires syncing 5 places, miss one and it breaks—and static checkers can't catch it(measured: one edit widening a hero squeezed zones into overlap and a border cut through content, yet validator + overlap-checker both reported 0 hard bugs, and only looking at the figure revealed it).

The solution isn't to add more detection, it's to change how you write it. Experts write TikZ bywriting a constraint graph(relative positioning + fit + matrix), letting the layout engine compute positions—collisions are impossible by construction, the figurecorrect by construction, not correct-after-review.

Evidence:references/examples/ the same 5-stage pipeline, with an absolute-coordinate version (BAD) and a by-construction version (GOOD), rendersvisually equivalent; but applying the same most natural edit (widening the hero / lengthening a label), BAD breaks while GOOD automatically reflows. See proof-edit-safety-hero-widen.png。

Core principle: LAYOUT BY CONSTRUCTION, not BY COORDINATE

Scope: by-construction discipline applies to themacro skeleton layer(how modules/zones are placed relative to each other and connected). Inside embedded viz(a heatmap cell by cell, bar charts) you can continue to draw locally by hand—it's self-contained and a wrong coordinate doesn't cascade— but you must use \begin{scope}[shift={(parent.center)}] to anchor it to the parent node, so it moves with the parent node.

5 idioms (you must follow them—a prose guide can't convey layout skill, copy these code snippets)

① Define the layout rhythm in only one place

The same spacing/row height/column widthis defined only once, referenced everywhere. Never copy the same number in multiple places.

\newlength{\stagew}\setlength{\stagew}{4.5cm}   % 改一处,全图跟着变
\def\gap{0.5cm}
\tikzset{node distance=\gap}

② Place modules with relative positioning, not absolute at (x,y)

The first is anchored, the rest right=of / below=of the previous one. The spacing lives in node distance one place.

\node[zone] (s1) at (0,0) {};
\node[zone, right=of s1] (s2) {};      % ✅ 间距由 node distance 决定
\node[zone, right=of s2] (s3) {};      % 加宽 s2 → s3 自动右移
% ❌ \node[zone] (s2) at (5,0) {};      % 手填 5 = 改 s1 宽度就得改这里

Use \matrix of nodesfor grids/tables, use chains——Don't manually add 2cm to x.

③ Connect lines to node anchors, never re-copy boundary coordinates ← the single biggest win

\draw[arrow] (s1.east) -- (s2.west);   % ✅ 任何重排下都不会错位
% ❌ \draw[arrow] (4.5,5) -- (5.0,5);   % 把 zone 边界又抄了一遍 = 改布局就断

If arrows reference nodes, they can never be misaligned. This one alone eliminates more than half the bugs in the review loop.

④ Use fitfor containers, and text widthfor labels (wrap) instead of minimum width(which stretches)

\node[fit=(a)(b)(c), draw, rounded corners] {};         % zone 自动包住内容
\node[box, text width=3.2cm, align=center] {长标签会换行不会溢出};
% ❌ minimum width=3.2cm → 长标签把框横向撑大、顶破 zone

text width lets overly long contentwrap(keeping the box width),minimum width lets the boxgrow outward(overflowing into neighbors). The former downgrades a "collision bug" (hard, must fix) into "a bit cramped" (soft, aesthetic).

⑤ Center as a whole using calc midpoint, don't compute by hand

\coordinate (c) at ($(first.north west)!0.5!(last.north east)$);
\node[anchor=south] at ($(c)+(0,0.5)$) {标题};   % 行变宽,标题自动跟着居中

8 hard constraints (violating any guarantees failure — load references/hard-constraints.md to see all)

The most frequent ones (many are silent CJK / xelatex pitfalls):

  • ⚠️ On a CJK node, rotate=90 → renders as unreadable color blocks. All Chinese labels must be horizontal.
  • ⚠️ \texttt{…中文…} → error.\texttt only wrap pure English code.
  • ⚠️ xelatex silently fails on missing fonts → after compiling you must grep "Missing character" *.log; non-zero = font wasn't resolved (often CJK).
  • ⚠️ Adding -- to a single straight rounded corners segment → endpoint ghost arcs. Only use on polylines with ≥2 segments / |- .
  • ⚠️ A path has bends but no \usetikzlibrary{bending} → the arrow tip on the bent path will inevitably be mis-aligned.
  • ⚠️ (A.south) |- (B.west) when A.x falls within B's x range → the horizontal line pierces through B's interior (pierce). Use a waypoint to route around it or switch anchors.

Canonical arrows (don't hand-write -{Stealth[scale=X]})

Use predefined styles, only adjust line width(three levels: 0.6/1.0/1.6pt), the tip follows automatically. See ../thesis-figure-skill/references/tikz-template.tex 's 6 canonical styles. Iron rule:

  • < 1.5cm short arrowsmust use arrow short(tip 3pt), otherwise the default 6.5pt tip eats up the stem = "only a head left".
  • fan-out branching stubs use fan_stub(shorten <=0pt, flush against the spine with no gap), not arrow。
  • \usetikzlibrary{bending} must be loaded。

Workflow: write → lint → look at the image

bash references/lint.sh figure.tex

One entry point runs it all: ① tikz-validator (static before compiling: slight slopes/overflow/collisions) → ② xelatex compile → ③ missing-char gate → ④ pdf-overlap-checker (reports hard bugs vs candidates separately) → ⑤ design-linter (advisory). Exit code 0 = no hard bugs, 1 = hard bugs present.

The checker is a floor, not a ceiling. It eliminates the cheap 20% (compile errors, overlaps, known pitfalls), but can't catch the expensive 80% (whether the figure is memorable, whether numbers across panels are self-consistent, whether new geometry is correct).Even if lint passes, you must still look at the rendered PNG with your own eyes—— many breakdowns (zone overlaps, borders cutting through content) are completely invisible to static checks, and only show up when you look at the image.

When to use this skill vs thesis-figure-skill

What you want to do Use
Write/review any TikZ figure code, fix layout/alignment/overflow/arrow bugs, CJK rendering issues this skill
Turn paper text/reference figures into finished accompanying figures (design + orchestration + visual iteration + skeleton reuse) thesis-figure-skill (it composes this skill at the code-correctness layer)

thesis-figure-skill's 6 example-skeleton-*.tex All have been rewritten according to these 5 idioms; these are the best worked examples for this skill.

Load on demand

Trigger File
Want to see the complete code patterns for the 5 idioms references/by-construction.md
Want to see all 8 hard constraints + fixes references/hard-constraints.md
Want to compare before/after references/examples/(BAD vs GOOD + edit safety proof diagram)
Want to run static checks references/lint.sh(just execute, no need to Read)