| name | tikz-diagrams |
| description | Use this skill when an AI agent needs to create, edit, render, verify, improve, batch-generate, or stockpile TikZ/PGF diagrams or animations for LaTeX papers, Beamer slides, teaching material, research workflows, business/economics diagrams, or technical documentation. Triggers include TikZ, PGF, animate.sty, LaTeX animations, frame previews, GIF previews, LaTeX diagrams, Beamer figures, causal DAGs, flowcharts, curves, matrices, quadrant maps, decision trees, contact sheets, visual overlap checks, and diagram template libraries. |
TikZ Diagrams Skill
Create correct, polished, reusable TikZ diagram artifacts. Treat a diagram as an artifact, not just a snippet: write source, run static checks, compile, render, inspect visually, and repair severe defects before finalizing.
For visual and domain guidance, read only what is needed:
references/style_guidelines.md for spacing, typography, color, slide fit, and visual QA rules.
references/diagram_patterns.md when selecting a diagram family or mapping a user request to a template.
references/business_economics_patterns.md for economics, finance, econometrics, marketing, management, research, and teaching templates.
references/example_corpus.md when the user asks for examples, stock templates, regression tests, or evidence of what has worked well.
references/animation_workflow.md when creating TikZ/PGF animations, animate.sty PDFs, frame previews, GIF/MP4 previews, or animation stress tests.
references/tikz_gotchas.md when a compile, layout, label, or rendering problem appears.
references/clean_room_handoff_tests.md when preparing a fresh-session handoff, regression prompt, or iterative figure-series test.
references/critique_and_iteration.md when doing design critique, researcher-style revisions, noisy/composite figures, figure batteries, or multi-round visual review.
references/math_logic_checks.md when a figure contains equations, curves, equilibria, estimands, thresholds, game payoffs, geometry-dependent arrows, or model-implied comparative statics.
Tool Contract
- Prefer standalone
.tex files for individual diagrams.
- Use
xelatex by default. Use pdflatex or lualatex only when the project requires it.
- Use
scripts/check_tikz_safety.py before compiling new or edited diagrams.
- Use
scripts/compile_render.py to compile .tex to .pdf, render .png, and, when the diagram is not purely exploratory, run rendered visual QA with --visual-check.
- Use
scripts/check_tikz_visual.py when inspecting an already-rendered PDF for title-band collisions, text overlap, clipped labels, and crowded annotations.
- Use
scripts/make_contact_sheet.py for batches or iterations. Add --show-qa when visual QA reports exist.
- Use
scripts/render_tikz_series.py for controlled sequences of variants that update from a previous figure, such as teaching-to-research-to-compact versions.
- For animations, make both the interactive PDF and an inspectable frame preview when possible; PDF animation playback depends on the viewer.
- Save task outputs under a user/workspace output folder, not inside the skill directory.
- Final artifacts should normally include
.tex, .pdf, and .png. For batches, include contact sheets and a short QA log when useful.
- During critique or iterative visual review, save versioned PNGs and contact sheets instead of overwriting inspected images; stale viewer caches can otherwise show the wrong render.
- When showing an updated image in chat, prefer the freshly rendered versioned local file. Do not rely on a GitHub README image, browser tab, or overwritten canonical filename as proof that the user is seeing the latest render.
Resolve bundled scripts, templates, and references relative to the directory containing this SKILL.md. If the host agent exposes a skill-directory variable such as ${CLAUDE_SKILL_DIR}, use it; otherwise set SKILL_DIR=/path/to/tikz-diagrams in examples or commands.
Dependencies
Before running render workflows, check that the local environment has:
- Python 3.10+.
- Python packages:
Pillow for contact sheets and PNG validation; PyMuPDF (fitz) for rendered visual QA.
- A TeX distribution with
xelatex; use pdflatex or lualatex only when the project requires it.
- Poppler command-line tools, especially
pdftoppm, for PDF-to-PNG rendering.
ffmpeg for GIF/MP4 animation previews.
- ImageMagick
magick for contact sheets generated by the animation preview helper.
If a dependency is missing, ask before downloading or installing it. State the package name, source or package manager, why it is needed, and whether the workflow can continue with a reduced check instead.
Workflow
- Identify the target medium: paper, Beamer slide, handout, template library, or exploratory sketch.
- Choose presentation mode:
teaching, research, or compact.
- Identify the communication job: show mechanism, workflow, assumptions, feedback, comparison, diagnostic, risk, tradeoff, or evidence summary.
- Select a diagram family from
references/diagram_patterns.md or a domain template from references/business_economics_patterns.md.
- For algebraic, curve, equilibrium, statistical, game-theoretic, or geometry-dependent figures, run the math/diagram logic planning gate before drawing: identify variables, equations or constraints, expected signs, ordering, intersections, invariants, and whether the result is exact or schematic.
- For animations, first decide what changes over time, why animation is better than a static figure, whether the motion should be discrete or continuous, whether smooth transitions will materially increase render time, and how long viewers need to absorb each frame change; then read
references/animation_workflow.md.
- Start from
templates/standalone.tex unless a Beamer slide-fit wrapper is required.
- Write short labels first. Put longer explanation in external caption text, speaker notes, surrounding slide text, or a QA log rather than inside the rendered image.
- Run static checks.
- Compile, render, and run rendered visual QA.
- For direct labels, effect labels, estimate labels, callouts, or math notation inside a plotted region, run the targeted text-over-plot gate with
--text-plot-overlap or inspect equivalent PDF text boxes against rendered plot pixels.
- Inspect the PNG for overlap, clipping, blank output, cramped text, poor slide fit, confusing arrow flow, and model-logic problems that visual QA cannot detect.
- Run a design critique gate: decide
keep, simplify, split, or reject based on visual complexity, figure grammar, label economy, and whether the diagram says one clear thing.
- Patch the source or generator. Rerun checks and render after substantial layout changes.
- For multiple diagrams, create a contact sheet and inspect it before finalizing.
Editing Existing Figures
When editing an existing TikZ figure, inspect the current source and rendered output before changing layout. Preserve the established palette, typography, scale, coordinate system, and label style unless the user asks for a redesign.
For visual fix requests, start with the smallest plausible local change. Do not restyle the whole figure, move unrelated elements, or rewrite the diagram family unless the defect is structural.
When adding a node, label, arrow, panel, or data mark, extend the existing semantic styles, named coordinates, bounding boxes, legends, and contact-sheet/QA workflow as needed. If a change affects dependent geometry, update those dependencies together.
Presentation Modes
Use modes to decide how much explanation belongs inside the diagram:
- teaching: lecture or student-facing slide. Explainer boxes and teaching notes are allowed, but they need generous spacing and must not enter the title band, legend area, or key plot comparison.
- research: seminar, conference, working paper, or journal-style figure. Prefer direct labels, legends, axis labels, and concise annotations. Avoid large explainer boxes inside the plot area unless the user explicitly asks for them.
- compact: multi-panel figures, appendix grids, or constrained slide layouts. Use direct labels only; omit explainer boxes and long notes.
When the user has not specified a mode, infer from context. Use teaching for lecture materials and research for papers, seminars, and professional research presentations.
By default, do not render caption-style prose or interpretation paragraphs inside standalone images. Put that text in the QA note, surrounding document, speaker notes, or the calling agent's response.
Iteration Controls
For researcher-driven iteration, keep controls explicit instead of burying them in coordinates:
- Name important coordinates and nodes (
cutoff, effect_bracket, treated_label, legend_anchor) so specific elements can be moved without redrawing the whole figure.
- Separate semantic styles (
explainer, directlabel, researchlabel, teachingnote) from geometry.
- Offer paired variants when useful: a
teaching version with explainer boxes and a research version with direct labels and external captions.
- Preserve the same data geometry across variants unless the user asks for a conceptual redesign.
- Use visual QA reports to target edits: fix
title_band_collision, text_overlap, near_edge, and text_crowding issues one at a time.
- For fine-grained label collisions that ordinary visual QA can miss, especially effect labels on plots, use
--text-plot-overlap. This maps PDF text boxes onto the rendered image and checks whether targeted labels cover plotted strokes.
- For batches or repeated variants, create a contact sheet with
--show-qa and only inspect the failed or warning panels in detail.
- For critique rounds, distinguish a repair from a simplification or redesign. If the user says a figure is noisy, too complex, or should be redone, default to structural simplification or splitting, not a tiny coordinate tweak.
Template Selection
Select by communicative purpose rather than by visual appearance:
- flow/process: workflows, pipelines, reproducible processes, teaching sequences.
- DAG/causal graph: causal assumptions, confounding, mediation, selection, collider bias.
- axis/curve: supply-demand, thresholds, frontiers, response functions, forecasts.
- delayed-adjustment path / J-curve: time paths where a shock, intervention, or launch creates short-run friction, overshoot, deterioration, or muted response before recovery, catch-up, or a new steady state.
- matrix/grid: payoff tables, robustness checks, confusion matrices, risk matrices, specifications.
- quadrant map: segmentation, stakeholder maps, strategy matrices, prioritization.
- tree/branch: decisions, game trees, uncertainty, classification rules.
- stack/comparison: before/after, components, balance sheets, decompositions.
- feedback/convergence loop: iterative estimation, monitoring, learning, policy cycles.
- field/pressure: invisible forces such as tax pressure, incentives, liquidity stress, constraints.
- threshold/phase transition: nonlinear regime changes, crisis cliffs, tipping points.
- threshold/corridor trajectory: paths through feasible regions, survival corridors, safety bands, control limits, or exit thresholds.
- ensemble/aggregation: model voting, committees, forecasts, decision support.
Quality Bar
- No overlapping words.
- No clipped labels, arrowheads, legends, or notes.
- No unpositioned inline edge labels in dense diagrams.
- Short node labels are preferred; keep long prose out of the diagram.
- Keep caption prose out of the rendered image by default; record suggested caption text in a QA note or response.
- Arrows must express real semantics: causal, temporal, logical, transformation, diagnostic, or feedback.
- Visual plausibility is not enough for math, economics, statistics, or geometry diagrams. Curves, intersections, brackets, shaded areas, arrows, labels, and animation states must match the expected algebra, comparative statics, estimand definition, payoff logic, or model constraints.
- If exact equations, data, or parameter values are unavailable, mark the figure as
schematic in the QA note and avoid visual claims that look numerically exact.
- Use stable node dimensions (
text width, minimum width, minimum height, align=center) when labels can vary.
- Use a small semantic palette. Do not add decoration that does not clarify the concept.
- Do not add labels or annotations that merely repeat what a node, branch, arrow, or title already says.
- A single figure should usually use one primary grammar. Split DAG-plus-estimates, mechanism-plus-coefficients, or model-plus-diagnostics prompts into paired figures unless the shared layout clearly reduces complexity.
- One diagram should usually have one main teaching job.
- For delayed-adjustment paths, keep the time axis, intervention marker, baseline, and final direction easy to compare. Use short phase labels; put causal mechanisms, estimates, and caveats outside the rendered image or in a paired figure.
- Treat semantic correctness as part of visual QA: labels, highlights, arrows, and annotations must remain true in the frames, variants, or panels where they appear.
- Treat direct-label placement as part of visual QA: an effect, estimate, coefficient, or callout label must not sit on top of a curve, bracket, axis, shaded region boundary, or key comparison. If in doubt, rerender with
--text-plot-overlap and move the label to whitespace or add a clear backing box.
- For animations, every moving element must carry meaning. Do not animate for decoration; animate accumulation, transition, parameter sweep, threshold crossing, trajectory, sorting, recursion, or convergence.
- For animations, choose motion form deliberately: categorical additions usually need discrete build frames; accumulation, traversal, phase movement, and parameter sweeps usually need smooth intermediate frames.
- For animations, ask before rendering smooth transitions when smoothness materially increases render time or artifact size and the user has not already requested smooth motion. Offer a fast stepped preview versus a slower smooth render.
- For smooth animations that hit TeX memory limits, consider splitting the frame deck and stitching GIF/MP4 segments before simplifying away important motion.
- For threshold/corridor animations, keep regions, thresholds, legends, and axis scales stable. Reveal the path smoothly, then reveal exit/failure markers only after the crossing condition is true.
- For animations, timing is part of quality. Dense frames, new figure grammars, payoffs, legends, final takeaways, and threshold crossings need longer holds than simple highlights; the GIF/frame preview should use the intended pacing, not only one page per semantic state.
- For batches, diagrams must pass static checks, compile, render, and survive contact-sheet review.
Verification Commands
Set SKILL_DIR to the directory containing this SKILL.md.
Static check:
python3 "$SKILL_DIR/scripts/check_tikz_safety.py" path/to/diagram.tex
Compile and render:
python3 "$SKILL_DIR/scripts/compile_render.py" path/to/diagram.tex
Compile, render, and run visual QA:
python3 "$SKILL_DIR/scripts/compile_render.py" path/to/diagram.tex --visual-check --visual-mode teaching
Compile, render, and run targeted text-over-plot QA for labels such as effects, estimates, coefficients, or jumps:
python3 "$SKILL_DIR/scripts/compile_render.py" path/to/diagram.tex --visual-check --visual-mode research --text-plot-overlap
Visual QA on an existing PDF:
python3 "$SKILL_DIR/scripts/check_tikz_visual.py" path/to/diagram.pdf --mode teaching --report path/to/diagram-visual-qa.json
Target the fine-grained gate at custom label text when needed:
python3 "$SKILL_DIR/scripts/check_tikz_visual.py" path/to/diagram.pdf --mode research --text-plot-overlap --plot-label-regex 'tau|DiD|effect|estimate'
Batch contact sheet:
python3 "$SKILL_DIR/scripts/make_contact_sheet.py" path/to/pngs --output path/to/contact-sheet.png
Batch contact sheet with visual QA badges:
python3 "$SKILL_DIR/scripts/make_contact_sheet.py" path/to/pngs --output path/to/contact-sheet.png --show-qa
Animation preview from a frame-deck PDF:
python3 "$SKILL_DIR/scripts/render_animation_preview.py" path/to/frames.pdf --fps 8 --key-frames 1,10,20
Controlled figure series from a manifest:
python3 "$SKILL_DIR/scripts/render_tikz_series.py" path/to/series_manifest.json
Bounded Repair Loop
On first compile, render, safety, or visual-QA failure:
- Read the exact error or QA finding.
- Identify the smallest source region that caused it.
- Patch that region only.
- Rerun the exact failed check.
- Continue from the current source instead of rewriting the whole figure.
Do not loop indefinitely on similar failures. If the same class of failure persists after two focused repairs, reassess whether the figure should be simplified, split, or redesigned.
Iteration Policy
For ordinary single diagrams, do one focused visual repair pass after first render. Continue only if there is a severe defect: overlap, clipping, unreadable text, blank render, wrong semantics, or clear slide-fit failure.
When the user explicitly asks for iterative improvement, do the loop literally:
- Render current attempt.
- Inspect the screenshot.
- State the critique.
- Plan the next change.
- Implement and rerender.
Do not pre-generate "iterations" without inspecting the previous result.
During critique iterations, use versioned outputs such as figure_v01.png, figure_v02.png, and contact_sheet_v02.png. Only copy the accepted version to the final canonical filename after inspection.
When reporting back to the user, show or link the exact freshly rendered versioned local image that was inspected. If a canonical filename was overwritten, mention the versioned source as well; browser, chat, and GitHub image caches can otherwise display an older image.
Completion Criteria
Complete only when:
.tex source exists.
- Static check passes or any exception is documented.
- PDF compiles.
- PNG renders and is nonblank.
- Rendered visual QA passes, or any warning is documented and manually inspected.
- Fine-grained text-over-plot QA has passed or been manually inspected when labels are placed inside plotted regions.
- Visual inspection finds no severe overlap, clipping, or slide-fit issue.
- The design critique gate has a documented outcome:
keep, simplify, split, or reject.
- For math, curve, model, estimand, threshold, game-theoretic, or geometry-dependent figures, a math/diagram logic review is documented as
exact, schematic, needs_source, or failed.
- For animations, the intended frame sequence has been inspected through a frame deck, GIF/MP4 preview, or equivalent contact sheet, not only through the first rendered PNG.
- For batches, contact sheet exists and has been inspected.
In the final response, summarize the user-visible result and link the final output folder or final artifact files. Mention tests run and any limitation that remains.
Reference Corpus
Use a local curated example corpus when one is available. For business/economics deployments, a good corpus should include generated examples, category contact sheets, static checks, compile logs, render outputs, and a QA log.
If the user provides an example corpus path, store it only in task-local notes or environment variables such as TIKZ_DIAGRAMS_EXAMPLE_CORPUS; do not hard-code personal or institution-specific paths into reusable skill files.
Do not use quick smoke-test diagrams as visual exemplars. Smoke tests may prove the scripts run, but the example corpus above is the quality endpoint for template style and coverage.