Tables and Graphics
MetaPost
Learn how to use MetaPost for creating mathematical and technical vector graphics in LaTeX documents.
MetaPost is a vector graphics language related to METAFONT, designed by Donald Knuth. While METAFONT generates bitmap fonts, MetaPost produces encapsulated PostScript (EPS) files that can be imported into LaTeX documents. It excels at creating technical illustrations requiring mathematical precision.
Basic Syntax
A MetaPost program consists of assignments and drawing commands. The basic structure:
beginfig(1);
pair A, B;
A := (0,0);
B := (100,50);
draw A -- B;
endfig;
end
Compile with:
mpost filename.mp
This produces filename.1, filename.2, etc. (one file per beginfig/endfig block).
Drawing Primitives
Lines and Curves
beginfig(1);
% Straight lines
draw (0,0) -- (100,0);
% Bezier curves
draw (0,0) .. controls (30,50) and (70,50) .. (100,0);
% Quick curve shorthand
draw (0,0) {up} .. {right} (50,50);
endfig;
end
Filled Shapes
beginfig(2);
% Filled rectangle
fill (0,0) -- (100,0) -- (100,50) -- (0,50) -- cycle;
% Filled circle
fill fullcircle scaled 40 shifted (50,25);
% Filled elliptical shape
fill fullcircle xscaled 80 yscaled 40 shifted (50,25);
endfig;
end
Arrows
beginfig(3);
drawarrow (0,0) -- (100,0);
drawarrow (0,20) .. controls (50,40) .. (100,20);
drawdblarrow (0,40) -- (100,40);
endfig;
end
Text in MetaPost
MetaPost can typeset text using TeX:
beginfig(4);
label(btex Hello World etex, (50,25));
label.top(btex Top-aligned etex, (50,50));
label.bot(btex Bottom-aligned etex, (50,0));
endfig;
end
Variables and Expressions
beginfig(5);
% Numeric variables
numeric angle, radius;
angle := 45;
radius := 30;
% Pair variables
pair center;
center := (50,25);
% Subpath and time-based drawing
draw subpath(0,2) of fullcircle scaled 40 shifted center;
endfig;
end
Importing MetaPost into LaTeX
Use the graphicx package to include MetaPost output:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\includegraphics{filename.1}
\end{document}
Or use the luamplib package (LuaLaTeX only) for inline MetaPost, which compiles the code directly at build time with no separate mpost run or \includegraphics step needed:
\documentclass{article}
\usepackage{luamplib}
\begin{document}
\begin{mplibcode}
beginfig(1);
draw (0,0) -- (100,0) -- (50,50) -- cycle;
endfig;
\end{mplibcode}
\end{document}
When to Use MetaPost
| Use Case | Recommendation |
|---|---|
| Mathematical diagrams | MetaPost excels here |
| Flowcharts | Consider TikZ for easier syntax |
| Simple shapes | TikZ is simpler |
| Custom fonts | METAFONT (MetaPost's sibling) |
| Complex parametric curves | MetaPost is ideal |
Further Reading
- A User's Manual for MetaPost (included with TeX distributions)
- The MetaPost manual by John Hobby
- CTAN: metapost