# Integrating Metapost Graphics Into Latex Documents

## Getting Started with Metapost

Metapost is a powerful vector graphics language that can be used to create intricate illustrations, diagrams, charts, and schematics to integrate seamlessly into LaTeX documents. The metapost program converts the vector graphics code into encapsulated PostScript (EPS) files that LaTeX can render using the graphicx package. To get started, the Metapost interpreter and LaTeX with the graphicx package need to be installed and configured.

### Installing Metapost and Configuring LaTeX

The Metapost program is included in most TeX distributions. For example, in MiKTeX on Windows, installing the metapost package adds the mpost executable to the path. On Linux, metapost can be installed from the distro repositories, like the texlive-metapost package on Ubuntu and Fedora. LaTeX needs to be installed with support for EPS graphics such as via the graphicx package. The epstopdf package also aids conversion during document compilation. The configuration is done once to enable Metapost and LaTeX interoperability moving forward.

### Basic Metapost Syntax and Commands

Metapost code has similarities to the PostScript language. It uses declarative statements to draw 2D vector shapes like lines, arcs, curves and polygons by specifying points, widths and heights mathematically. The key commands include:

- draw: Draws a line between points
- fill: Draws and fills closed shapes
- label: Adds text labels
- linecap: Specifies line endings
- linejoin: Specifies joint shapes
- linewidth: Sets line thicknesses
- drawarrow: Draws arrow heads

These primitives allow constructing most types of graphical elements. The code is interspersed with algebraic formulae and calculations to precisely set coordinates, dimensions and styles programmatically.

### Creating Simple Drawings and Exporting as EPS

A simple Metapost document consists of declarative statements like:

draw (0,0)--(3cm,0); % Draws a line fill fullcircle scaled 2cm withcolor red; % Draws a filled circle label("Hello", origin); % Labels the origin point

The mpost command is used to process the Metapost code and output an EPS graphic file that can be imported into LaTeX:

mpost example.mp -output example

This evaluates example.mp, outputs the generated PostScript to example.1 and builds a tight bounding box in example.bb defining the margins.

## Including Metapost Graphics in LaTeX

To include Metapost graphics in LaTeX documents, the epsfig or the newer graphicx packages need to be used with options set to detect the tight bounding boxes:

### Using the “mpgraphics” package

The mpgraphics package simplifies inclusion of Metapost graphics. The graphics path is predefined eliminating the need for manually specifying paths. The \includempgraphics command inserts images with automatic bounding box detection:

\usepackage{mpgraphics} ... \includempgraphics{example}

### Setting the graphicx package options

Without mpgraphics, graphicx needs tight bounding box support enabled. This helps crop EPS graphics generated by Metapost to the optimal dimensions:

\usepackage[dvips, tightpage, plugins]{graphicx}

The tightpage option detects tight bounding boxes and plugins handles the PostScript graphics inclusion.

### Importing the EPS Graphics Files

With the configuration done, Metapost images can be imported by file name and formatted further:

\begin{figure}[h] \centering \includegraphics[width=0.3\textwidth]{example} \caption{Metapost Generated Graphic} \end{figure}

This inserts example.eps scaled to 0.3 times the text width with automatic margins.

## Positioning and Scaling Metapost Graphics

LaTeX provides flexible options for positioning, scaling, aligning and formatting imported Metapost graphics using various containers like boxes, minipages and tables:

### Using LaTeX Boxes and Minipages

Boxed containers help position graphics precisely by defining widths and aligning horizontally or vertically:

\begin{minipage}{0.5\textwidth} \includegraphics[width=\linewidth]{example} \end{minipage}

This embeds the EPS in a minipage spanning 50% text width. The graphic is scaled to fit the minipage automatically.

### Setting the height, width, scale Parameters

The graphicx command has height, width, scale options to customize the rendering further:

\includegraphics[height=5cm, width=10cm, scale=0.5]{example}

Here the image is forcibly scaled and sized overriding the tight bounding box. Useful when manual tweaks are needed.

### Aligning Graphics with Text and Equations

Aligning Metapost graphics with text blocks and equations provides flexibility in positioning:

\begin{wrapfigure}{r}{0.25\textwidth} \includegraphics[width=\linewidth]{example} \end{wrapfigure} Text can wrap around graphics using wrapfigure environments. Equations can also be aligned beside graphics using various column and minipage ratios...

This aligns the graphic right with 25% width allowing text to wrap around conformantly.

## Advanced Techniques

Further customization involves directly passing LaTeX document details like lengths, nodes and coordinates into the Metapost code for tight integration:

### Passing LaTeX lengths and nodes to Metapost

Key LaTeX lengths stored in dimen registers like \textwidth can be used in Metapost for alignments:

\newdimen\mpdim \setlength{\mpdim}{\textwidth} \begin{mpost*} dimen:=\mpdim; draw (0,0)--(dimen,0); \end{mpost*}

Here \textwidth is retrieved and passed into Metapost dynamically to draw a line spanning the whole text block width.

### Drawing Schemes and Diagrams with Metapost

Metapost contains advanced modules for drawing charts, schemas, circuit diagrams, flow charts and other intricate illustrations. For example, logic gate symbols, shapes and topology can be encoded to generate specialized graphics on the fly:

input modules; vardef AND_gate(expr p, n) = begingate(p, n); and_gate(Up); endgate; enddef; draw AND_gate((0,0), 2); % Draws an AND gate

The inbuilt modules have utilities for mathematical plots, graphs, network diagrams, electric circuits and illustrations drawings.

### Automating Graphics Generation with Scripts

Complex graphics can be scripted for algorithmic drawing by parametrizing key attributes:

input graphs; numeric width; width=10; numeric height; height=8; drawcontour(log(x+y), (0,0),(width,height),20); axes("(0,0)", "(width,height)", "x", " f(x,y)");

Here the graph plotting is abstracted using variables for bounds, sampling density and axis labels. Wrapping it in a script macro allows programmatically creating an entire graphics library.

## Debugging Issues with Metapost and LaTeX

Integration issues may arise with incompatible packages, unsuitable options or syntax errors that require debugging:

### Fixing Bounding Box Issues and Crop Problems

Incorrect bounding boxes lead to clipped or incorrectly framed graphics. Using tight bounding boxes generated from Metapost fixes this:

mpost -interaction=batchmode example

Batch mode forces output of tight bounding boxes. Cropped edges indicate nested beginfig/endfig statements or leftover artifacts. Verifying syntax helps.

### Handling Missing Font and File Issues

File not found errors can happen if graphics path is incorrectly resolved or fonts are missing. Using full path names fixes file issues. Distribution fonts like Times/Helvetica instead of system fonts resolve issues.

### Version Incompatibilities

Package version conflicts between Metapost, LaTeX (with epsfig/graphicx) and the distiller can also causemalformations. Standardizing distribution with TexLive or MiKTeX minimizes conflicts.

## Next Steps with Metapost

With a firm grasp over Metapost integration with LaTeX, advanced use cases around dynamism, automation and smart graphics become accessible:

### Creating Animations and Interactive Diagrams

Metapost empowers creating animated and interactive graphs, charts and illustrations by scripting parametrized builds over keyframes:

input graphs; numeric t; t=0; numeric x; x=0; beginfig(1); draw options(t=0,x=0); endfig; for i=1 upto 10: beginfig(i); draw options(t=i/2, x=sin(t)); endfig; endfor

Here the sine wave form gets drawn over 10 frames by looping over the parameters. Automation provides flexibility for custom animations.

### Integrating with Other TeX Packages

Tight integration with MATLAB/Octave, Gnuplot or R allows feeding data from scientific toolchains into Metapost for seamless technical illustrations.

data = load("output.dat"); draw data_plot(data, geometric); axes_scale("Linear");

Here output data is imported and charted using stylistic attributes enabled via backend integration with the toolchain ecosystem.

### Building a Graphics Library

A templatized library of parametrized graphics code enables reusability:

input graphs; def polygon(expr n, vertices) = for i=1 upto n: draw vertex[i]--vertex[(i % n) + 1] endfor enddef; beginfig(1); polygon(5, ((0,0),(1;60),(1;120),(1;180),(1;300))); endfig;

The polygon macro abstracts away positional details while allowing runtime configuration via custom parameters.

In conclusion, Metapost offers extensive and powerful graphics capabilities that integrate elegantly into LaTeX documents for publication-quality outputs spanning diagrams, schematics, plots, illustrations, and technical drawings.