Creating Vector Graphics Programmatically With Metapost

What is Metapost and Why Use It?

Metapost is a programming language for creating precise vector graphics programmatically. It excels at typesetting mathematical illustrations and diagrams. Metapost outputs PostScript code that can be interpreted by PDF viewers and printers.

Key reasons to use Metapost include:

  • It is highly suited for generating graphs, charts, diagrams common in technical documents
  • The language has powerful abilities for precise coordinate positioning, transformations, clipping, fills, etc.
  • The vector output integrates seamlessly with LaTeX documents
  • The macros and procedural capabilities enable automation and efficient re-use

If you need to include geometrical illustrations in documents where precision is important, Metapost provides an automated solution superior to manually created graphics.

Setting Up Your Environment

To start using Metapost, you will need:

  • A distribution like MikTeX (Windows) or MacTeX (Mac OS) that includes Metapost
  • A frontend editor like TeXworks that lets you easily run Metapost code

Metapost code is usually compiled to PostScript and then converted to formats like PDF. Make sure your editor has the workflow set up to be able to:

  1. Run Metapost code and output a PostScript file
  2. Automatically convert the PostScript to PDF, PNG, etc.

This enables a convenient edit-compile cycle for rapid Metapost prototyping.

Metapost Basics

Drawing Lines and Shapes

Metapost includes built-in commands for drawing basic graphical shapes:

  • draw - Draw a straight line between points
  • filldraw - Draw outline and fill shape
  • pickup - Save pen state
  • -- - Dash specifier

For example:

pickup pencircle scaled 1mm; % save pencil

draw (0,0)--(20,15); % line

filldraw (0,20)--(20,20)--(20,30)--(0,30)--cycle; % rectangle

draw (0,40){dir 45}..{dir 135}(20,40)--cycle dashed evenly; % triangle outline 

This will produce the basic line diagram with a line, rectangle and triangle.

Transformations

Common geometric transformations like scaling, rotations, and translations can be applied:

  • scaled - Scale object size up/down
  • rotated - Rotate object
  • shifted - Shift position
  • slanted - Shear transformation

These can be applied to points, paths as well as grouped graphical elements. For example:

draw (0,0){dir 45}..(20,0)--(20,20)--(0,20)--cycle; % parallelogram 

filldraw shift*(10,10) ((0,0)--(20,0)) scaled 2 slanted .5; % transformed

This generates a parallelogram and then makes a copy scaled, shifted and slanted.

Text and Labels

Text labels can be added using the label command. Font, color, size and other text formatting is controlled with TeX-like markup:

label(btex \color{red}\Large\bf Diagram Title etex, (0,10)); 

label.rt(btex $x$ axis etex, (10,0));

The label positions can be relative to a point or aligned along a coordinate axis.

Creating a Simple Graphic

Let's put together the basics we've seen to create a simple diagram with labelled axes, arrows, and geometric shapes:

pickup pencircle scaled 1mm; 

drawdblarrow (-20,0)--(100,0); % x axis
label.bot(btex $x$ etex, (100,0));

drawdblarrow (0,-20)--(0,100); % y axis  
label.lft(btex $y$ etex, (0,100));

% shapes
fill fullcircle scaled 20 shifted (50,50) withcolor red; 
filldraw fullcircle scaled 15 shifted (30,30);

dotlabel.rt(btex Red circle etex, (70,70)) ;
dotlabel(btex Blue circle etex, (45,45));

This creates a diagram with x and y axes, labels, a red filled circle, and blue outlined circle - each with text callouts.

By building up graphical components like this, intricate technical diagrams with precision placement can be accurately generated.

Integrating with LaTeX

A major benefit of Metapost is the ease of integrating graphics within LaTeX documents. This is done via the mpost inclusion macro:

\documentclass{article}
\usepackage{graphicx}

\begin{document}

Some text before the image. 

\begin{figure}
\centering
  \mpost{
    draw fullcircle scaled 3cm; 
  }
\end{figure}

More text after the image.

\end{document}  

On compilation, the Metapost code is extracted into an MPS file, processed, and replaced with the resulting graphical output - neatly embedded into the final PDF.

Packages like mpgraphics streamline this further with shortcuts for common options.

Advanced Techniques

Clipping and Filling

Metapost has powerful clipping and filling operators:

  • clip - Restrict rendering to path
  • fill - Fill shape with color
  • unfill - Remove fill color

For example, clipping text to a circular boundary:

pickup pencircle;
path c; 
c = fullcircle scaled 50 shifted (50,50);

clip c;
label(btex Clip me to the circle! etex, (0,30));

And filling between two polygon boundaries:

path outer, inner;
outer = (0,0)--(100,0)--(100,100)--(0,100)--cycle; 
inner = (25,25)--(75,25)--(75,75)--(25,75)--cycle;

fill outer--inner withcolor .6white;
draw outer; draw inner; 

Mathematical Functions

Metapost incorporates mathematical functions for plotting graphs and integrating with technical illustrations:

pickup pencircle scaled 1bp;

numeric x, y; 
x = -5; 

draw plot(x, x^2) for x=-5 upto 5; 

label.top(btex $y = x^2$ etex, (5,25));

Transformations can also leverage built-in functions like sine, cosine and logarithms.

Animations

By wrapping Metapost code in a LaTeX macro, simple animations can also be created as enumerated parameter variations. For instance, a bouncing ball animation:

\newcommand{\bounce}[1]{
  \mpost{
    numeric t; t = #1;
    fill fullcircle scaled 20 shifted (t*5, 100-t*t*2) withcolor red; 
  }
}

\bounce{0} \bounce{1} \bounce{2} \bounce{.5} %....

By changing the input parameter across multiple macro calls, an animated sequence is produced in the output PDF.

Troubleshooting Common Issues

Some typical problems and solutions:

  • Compilation errors - Enable log file output from your Metapost compiler. Fix errors sequentially.
  • PDF not updating - Clean auxiliary output files to force rebuild.
  • Positioning issues - Metapost uses PostScript style coordinates. Origin at lower-left with up as the positive y direction.
  • Text rendering problems - Enable font expansion and set TFM font flag to get smooth text.

Also leverage online documentation and communities to get answers for specific challenges.

Additional Resources

For further learning, check out these excellent resources:

  • The Metapost Manual - Thorough documentation of all language features
  • LaTeX Graphics Companion - Great examples of integrating Metapost graphics
  • Metapost Preamble - Collection of useful Metapost templates and utilities
  • TeX SE Q&A site - Active community for Metapost help

With practice, Metapost enables you to automate publication quality technical graphics integrated seamlessly with LaTeX.

Leave a Reply

Your email address will not be published. Required fields are marked *