codefig
Paper figures as code: no coordinates, real column widths, a linter for figures.
Compose architecture, memory, pipeline and attention diagrams in Python. Design at print size, inspect the result, and keep the source alongside your paper.
Quickstart · Gallery · Why · Docs · AI
Flagship example
An original disaggregated LLM serving design with nested GPU/CPU groups, an overlap timeline, and illustrative throughput–latency curves. Read the source.
Why codefig
Drawing a paper figure often means nudging boxes in draw.io or PowerPoint, then discovering that LaTeX scaling made the labels 4 pt tall. TikZ makes the source reviewable, but detailed placement can still take time. Colours drift between panels; every reviewer comment can trigger another redraw.
codefig makes the composition explicit and checks the exported result:
- Layout instead of coordinates: describe rows, columns, groups and relationships.
- Real venue widths: choose the final column or text width before drawing.
- Publication defaults: shared typography, stroke roles and semantic categories.
- Figure lint: catch small text, collisions, missing keys and export problems.
- Reviewable Python: version the structure, labels and data with your manuscript.
An honest comparison
✅ natural strength · ⚠️ possible with setup or tradeoffs · ❌ not the intended workflow. This is a workflow comparison, not a benchmark of every extension.
| Capability | codefig | matplotlib | TikZ | draw.io | Mermaid | Graphviz |
|---|---|---|---|---|---|---|
| No manual coordinates | ✅ | ⚠️ | ⚠️ | ⚠️ | ✅ | ✅ |
| Diffable code/text source | ✅ | ✅ | ✅ | ⚠️ XML | ✅ | ✅ |
| Layout at real venue width | ✅ presets | ⚠️ figsize | ✅ TeX | ⚠️ | ⚠️ | ⚠️ |
| Built-in paper figure lint | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
| Publication theme | ✅ | ⚠️ styles | ✅ control | ⚠️ | ⚠️ | ⚠️ |
| CVD-safe palette workflow | ✅ | ✅ palettes | ⚠️ | ⚠️ | ⚠️ | ⚠️ |
| Rich data plotting | ⚠️ embedded charts | ✅ | ✅ PGFPlots | ❌ | ⚠️ | ❌ |
| Freehand editing | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ |
| Huge auto-laid graphs | ❌ | ❌ | ⚠️ | ⚠️ | ⚠️ | ✅ |
| Gentle learning curve | ⚠️ Python | ⚠️ Python | ❌ | ✅ | ✅ | ⚠️ DOT |
| Ecosystem maturity | ⚠️ pre-1.0 | ✅ | ✅ | ✅ | ✅ | ✅ |
| Ultimate typography/control | ⚠️ | ⚠️ | ✅ | ⚠️ | ⚠️ | ⚠️ |
When NOT to use codefig
- Use matplotlib for exploratory analysis, scientific axes and specialised plots.
- Use draw.io for direct mouse editing and unconstrained visual sketches.
- Use Graphviz for large automatically laid-out dependency graphs.
- Use TikZ when precise TeX typography and unrestricted control dominate.
- Use Mermaid when a short Markdown diagram is the whole requirement.
Quickstart
pip install codefig
Three boxes, two semantic categories, two edges, and an automatic legend.
from codefig import Figure, Box, Row, Col, Diagram, Edge, Legend
fig = Figure(venue="icml", width="column", panel_caption="none")
enc = Box("Encoder", category="model")
kv = Box("KV cache", category="memory")
dec = Box("Decoder", category="model")
body = Col([Col([enc, kv, dec], gap=18), Legend(direction="row")], gap=10)
with fig.panel("a") as p:
p += Diagram(body, [Edge(enc.port("bottom"), kv.port("top")),
Edge(kv.port("bottom"), dec.port("top"))])
alt = "Encoder writes a KV cache read by the decoder."
print(fig.lint(alt=alt))
fig.save("quickstart.png", alt=alt)
fig.save("quickstart.pdf", alt=alt)
codefig lint (icml, 234 pt): 0 error(s), 0 warning(s), 0 info
The example uses a vertical composition to fit a column without shrinking labels.
Change the labels and categories first; let the containers handle placement.
Legend() collects the categories automatically.
Include the PDF at its native width:
\includegraphics{quickstart.pdf}
Do not add a width here: the PDF is already designed at the exact column width. Keeping that size preserves the intended 6–8 pt theme typography. If the composition grows too wide, reflow it and re-lint rather than scaling it down.
Gallery
Original demonstrations and cookbook recipes; click an image for runnable source.
Memory and serving Tables, attention matrices and routed pools. |
Schedules and operators Timelines, pipeline bubbles and code blocks. |
Serving cluster Groups and branching connections. |
Solids and pyramid Cuboids, slabs and hierarchy. |
Embedded charts Themed data inside a diagram. |
Block-sparse matrix Unequal tracks and split lines. |
Migration timeline Tasks and migration spans. |
Wrapped flow Charts beside a folded chain. |
KV cache Structured cache blocks and ports. |
Browse all 31 recipes · Cookbook index
Features
Layout primitives
| Category | Public primitives |
|---|---|
| Composition | Row, Col, Grid, Group, Stack |
| Nodes | Box, Text, Circle, Diamond, Triangle, Polygon |
| Structured data | Matrix, TokenStrip, Table, DotGrid |
| Repetition | Stacked, Repeat, Series |
| Spatial structure | Region, Cuboid, SlabStack, Pyramid |
| Sequences | WrapFlow, Tree, Timeline, Lanes |
| Annotation | Brace, Callout, Badge, Step, Dim, CodeBlock |
| Connections and keys | Diagram, Edge, Guide, Fork, Join, Legend |
Compose small containers, then combine them into panels.
Use Region for overlapping membership rather than forcing everything into nested groups.
WrapFlow folds a long chain; Matrix expresses cell structure directly.
See layout concepts for composition rules.
Constraints
same_x,same_y: share an alignment axis.same_width,same_height: equalise dimensions.align_columns,align_rows: share tracks across matrices and token strips.above,below,left_of,right_of: express relative placement.place,distribute,align: place and space related elements.
Use constraints for relationships across containers, not as a coordinate substitute. Read constraints before combining many relations.
Edges & routing
- Attach edges to visible nodes with
node.port("right")and other side ports. - Sliding ports and edge alignment can straighten small offsets.
- Fan-in trunks share a route;
Edge(trunk=False)opts out. ForkandJoinexpress explicit branching and merging.Edge(via=...)passes through an operator.Guidedraws a helper line without pretending to be a data arrow.Diagram.zoomconnects an overview to a magnified detail.
Dense crossings still need visual inspection. Changing the ordering or leaving a routing channel often helps more than adding bends.
Charts
| Primitive | Intended use |
|---|---|
BarChart |
A compact bar comparison |
GroupedBarChart |
Multiple series, horizontal bars or baseline comparisons |
StackedBarChart |
Composition of totals |
LineChart |
Trends, including error bands |
Sparkline |
A small trend embedded beside a label |
These are themed codefig primitives, not matplotlib wrappers. They share the figure's typography and visual language. Use log scales for values spanning decades and error bars or bands for uncertainty. For a specialised scientific plot, use a plotting library instead.
Themes & venues
The paper theme documents 6/7/8 pt annotation/label/title roles,
0.6/0.75/1.2 pt box/arrow/emphasis strokes, and a CVD-safe categorical palette.
Use category= and Legend() for meaning; reserve accents for emphasis.
The classic theme supports older scripts and a larger screen-oriented appearance.
Preset dimensions below come from venues.py; they are template presets, not a
promise that every year's author kit will remain unchanged. Check your submission template.
| Venue | Column width (pt) | Text width (pt) |
|---|---|---|
neurips |
— (single column) | 396 |
iclr |
— (single column) | 396 |
icml |
234 | 486 |
mlsys |
234 | 486 |
vldb |
239.76 | 504 |
sigmod |
239.76 | 504 |
osdi |
240.12 | 504 |
sosp |
239.76 | 504 |
Aliases include acm for SIGMOD and usenix, nsdi, fast, atc for OSDI.
For NeurIPS and ICLR, use width="text"; width="column" requires a two-column preset.
See themes and venues.
Lint
38 rules inspect the figure at its final width. Examples:
| Rule | What it catches |
|---|---|
CF-TXT-001 |
Text too small at final width |
CF-TXT-007 |
Label overflow or insufficient padding |
CF-TXT-010 |
Drawn text covered or struck through |
CF-COL-004 |
Semantic categories without a key |
CF-ARR-003 |
Edges attached to invisible containers |
CF-REG-001 |
A region covering a non-member |
CF-LAY-004 |
Aspect ratio outside the slot's suggested range |
CF-EXP-001 |
Width mismatch or excessive shrink |
save() refuses export on lint errors under the default venue lint policy.
It writes a <name>.lint_preview.png with findings outlined so you can inspect the problem.
Warnings and info findings still deserve attention; lint cannot judge the scientific story.
See the complete rule reference.
Export
- PDF: vector output with embedded TrueType subsets; no Type 3 fonts.
- SVG: text remains text, with alt text in the document title.
- PNG: 300 dpi by default for physical figures; configure
dpi=as needed. alt=writes a companion.alt.txtfile.layout_report()returns fitting diagnostics for debugging layout.
Keep Python as the authoritative source, and regenerate every format from it.
Lint in action
Six stages in one row, one colour each, squeezed into a 234 pt ICML column. Lint tells you exactly what is wrong, by how much, and what to do:
from codefig import Figure, Box, Row, Col, Legend
fig = Figure(venue="icml", width="column", panel_caption="none")
stages = ["Tokenize", "Embed", "Encode", "Attend", "Decode", "Sample"]
with fig.panel("a") as panel:
panel += Col([Row([Box(s, category=s) for s in stages]), Legend(direction="row")])
print(fig.lint(alt="A six-stage pipeline squeezed into one column."))
codefig lint (icml, 234 pt): 0 error(s), 2 warning(s), 2 info
WARN CF-EXP-001 content is 250 pt wide but the slot is 234 pt: everything shrinks ×0.94 (fonts 5.6–7.5 pt) — use width='text', cols=, or fewer/shorter boxes; …
fix: Figure(venue=..., width='column'|'text') and \includegraphics at scale 1; see docs/cookbook/30_compact_column.py
WARN CF-TXT-001 6 text run(s) below 6 pt at final size (smallest 5.61 pt) [text:'Attend', text:'Decode', text:'Embed' …]
fix: use the theme size roles (6/7/8 pt); widen the figure (width='text') or shorten labels
INFO CF-COL-001 5 categorical hue families [#4DB1F2, #FCD188, #8FCCA7 …]
INFO CF-LAY-004 aspect 6.63 outside 1.1–2.5 for a column-width figure
The fix is structural, not cosmetic: two rows, and categories that mean something (at most 4). Warnings are gone, fonts stay at the theme's 6/7/8 pt roles:
from codefig import Figure, Box, Row, Col, Legend
fig = Figure(venue="icml", width="column", panel_caption="none")
kind = {"Tokenize": "data", "Embed": "model", "Encode": "model",
"Attend": "attention", "Decode": "model", "Sample": "data"}
boxes = [Box(s, category=c) for s, c in kind.items()]
with fig.panel("a") as panel:
panel += Col([Row(boxes[:3]), Row(boxes[3:]), Legend(direction="row")])
print(fig.lint(alt="A six-stage pipeline in two rows."))
codefig lint (icml, 234 pt): 0 error(s), 0 warning(s), 1 info
INFO CF-LAY-004 aspect 3.37 outside 1.1–2.5 for a column-width figure
AI-first authoring
LLMs can describe rows, groups and connections without guessing spatial coordinates. Lint findings carry rule identifiers and suggested fixes, giving an author a concrete repair loop. This reduces placement guesswork; it does not remove the need to inspect the rendered PNG.
The quick card is ~12.9 KB; the full reference is ~276.0 KB (decimal KB). Choose the short card first, then retrieve relevant sections of the full reference.
| File | Role |
|---|---|
| llms.txt | Small entry point and authoring rules |
| llms-full.txt | Consolidated reference |
| AGENTS.md | Authoring and development workflow |
| CLAUDE.md | Assistant entry point |
| API | Real constructors and arguments |
| Cookbook | Copy a working composition |
Paste this into Claude Code, Cursor or Codex:
Create an original codefig diagram for the system I describe.
1. Read llms.txt and AGENTS.md. Confirm the intended venue and column/text width.
2. Open the cookbook index and choose the nearest working recipe.
3. Use documented primitives and semantic categories with Legend().
Do not guess constructor arguments or introduce absolute coordinates.
4. Keep labels short. Compose Row/Col/Grid before adding cross-container constraints.
5. Print fig.lint(alt=ALT). Apply each finding's suggested fix.
Repeat until there are 0 errors and 0 warnings; inspect info findings too.
6. If save refuses, inspect the generated lint_preview.png before guessing.
7. Render and VIEW the PNG at print width. Check the story, routes and labels.
8. Export PDF, SVG and PNG with descriptive alt text. Keep the Python source.
9. Include the PDF in LaTeX at native size, with no width override.
For a chat AI: “Read the attached llms.txt; use llms-full.txt as reference and help me build a lint-clean codefig figure.”
Measured AI usability
Fresh AI authors received only public docs and reproduced six published systems/ML figures. An independent scorer applied a 100-point rubric:
- A: outcome, 60 points: structural fidelity 30, visual quality 15, lint 10, code 5.
- B: process friction, 40 points: authoring friction and repair process.
| Target | Figure | 0.15 independent | 0.16 independent |
|---|---|---|---|
| t1 | ServerlessLLM | 80 | 64.6 |
| t2 | Lero | 81 | 82.5 |
| t3 | MegaBlocks | 89 | 87.5 |
| t4 | Llumnix | 89 | 91.0 |
| t5 | Gated Attention | 81 | 72.0 |
| t6 | RETRO | 74 | 72.5 |
| Mean | 82.3 | 78.4 |
The 0.15 independent median was 81.0. The 0.16 mean regressed by 3.9 points, concentrated in column-width targets t1/t5. The other four independent deltas were within ±2 points. This is six targets with one author sample each; scorer models differed, so calibration may explain part of the difference. A successful process exit does not imply a lint-clean or structurally faithful figure.
What the findings changed
- Drawn-text collisions motivated
CF-TXT-010. - Refused exports without a diagnostic image motivated
lint_preview.png. - Missing magnification and helper lines motivated
Diagram.zoomandGuide. - Width guesswork motivated diagnostics naming the widest layout chain.
- The retest exposed compact-recipe discoverability and
widths=confusion.
Column fitting and compact-before-shrink behaviour remain priorities. These results are a feedback loop, not a claim of autonomous publication quality. The target paper figures are not redistributed; this README includes no eval images.
Install
pip install codefig
# From a source checkout:
pip install -e .
# Development dependencies:
pip install -e ".[dev]"
| Platform | System Cairo setup |
|---|---|
| Linux / Debian / Ubuntu | sudo apt install libcairo2 |
| macOS / Homebrew | brew install cairo |
| Windows | Install Cairo via conda-forge (conda install -c conda-forge cairo) or a GTK runtime; make its DLLs discoverable |
CairoSVG requires the system Cairo library in addition to Python packages. Use a virtual environment to isolate the Python dependencies.
FAQ
Is this a matplotlib replacement?
No. It focuses on composed paper diagrams and compact embedded charts. Keep matplotlib for rich scientific plotting and exploratory analysis.
Can I edit the SVG?
Yes, in an SVG editor. Text remains text, but external edits are not imported back into Python. Keep the source if you want reproducible regeneration.
What about fonts?
The paper theme uses a sans stack and 6/7/8 pt roles. PDF export embeds TrueType subsets. Inspect the result on your actual machine; font availability can affect metrics. The lint reference describes PDF font checks.
Does it work in Jupyter?
You can run the Python API and display a saved PNG or SVG using notebook tools.
There are no _repr_svg_ or _repr_png_ hooks for automatic rich display.
Can I use the output in Overleaf?
Export PDF locally, upload it, and use \includegraphics{quickstart.pdf}.
Keep the native size so the designed print typography is preserved.
Is the API stable?
This is pre-1.0 software. Pin the version for a paper and keep the generating script. Review changes before upgrading a manuscript's build environment.
Documentation
| Read | Purpose |
|---|---|
| Getting started | First figure and lint loop |
| Layout | Composition primitives |
| Constraints | Relationships across containers |
| Themes and venues | Print typography and width presets |
| Fit a column | Diagnose width pressure |
| Cookbook | 31 runnable recipes |
| API | Public constructor reference |
| Lint rules | All 38 rules and suggested fixes |
| Feature tour | Broader examples and capabilities |
Roadmap
Plans, not promises; priorities follow observed authoring friction.
- Compact or reflow before shrinking below readable type sizes.
- Make compact-column recipes easier to discover.
- Clarify width budgets and spare-space semantics of
widths=. - Improve dense routes, annotation placement and diagnostics.
- Continue fresh-author evaluations and report regressions honestly.
Contributing
Start with CONTRIBUTING.md. A useful bug report includes a minimal script, version, venue and lint output. For new recipes, include descriptive alt text and inspect the rendered PNG. Only submit diagrams and assets you have the right to redistribute.
python -m pytest -q -W error
python tools/gen_api_docs.py
If codefig helps your paper, star the repository or share an original figure and its source.
Citation
@software{codefig2026,
author = {justinhk001},
title = {codefig},
year = {2026},
url = {https://github.com/justinhk001/codefig}
}
License & acknowledgements
MIT. Copyright (c) 2026 Justin.
Thanks to Tabler Icons (MIT), kiwisolver (Cassowary constraint solving), and CairoSVG (vector/raster export).
Metadata
Release files for codefig 0.18.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| codefig-0.18.0.tar.gz | 1.2 MB | Without provenance | Details for codefig-0.18.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| codefig-0.18.0-py3-none-any.whl | Python 3 | none | any | Details for codefig-0.18.0-py3-none-any.whl |
Total release size: 2.3 MB
Release files / codefig-0.18.0.tar.gz
| Download URL | codefig-0.18.0.tar.gz |
|---|---|
| Size | 1.2 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
06a595f83abbc7ca417289d3adc098277dbe3e1169cfb4754d5213a319b5bd93
|
|
BLAKE2b-256 checksum How to use checksums |
01bad5dbac4159c1bdb517999201bd363d4f9529b273f98983fee30416b4cb98
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.5
|
Release files / codefig-0.18.0-py3-none-any.whl
| Download URL | codefig-0.18.0-py3-none-any.whl |
|---|---|
| Size | 1.1 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
275bbf4f878d5ddeda6257402c3ca2a3ec49f86473bdd7e448dfbd6d6f2102e8
|
|
BLAKE2b-256 checksum How to use checksums |
998bc7dbaafcce72371532b6da9b3e99c6a973d16a2b672eeb87fa5b1995a372
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.5
|
Security for codefig 0.18.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.