One of the most compelling aspects of LaTeX is it's resemblance to a programming language. Here we demonstrate how to take advantage of LaTeX command definition in order to include figures in our documents and reuse code.

In LaTeX one can define new commands and environments, use conditionals and declare variables in order to produce clean, configurable and versatile source files. In many programming languages, developers strive to encapsulate common logic in functions and LaTeX is no different. You can, and should, define your own commands (\newcommand or \renewcommand).

An example of a LaTeX construct

This is the code that's needed in order to include a figure in a document:

  \caption{This is a figure example.}\label{fig:myfigure}

This code inserts the figure found in the file figs/myfigure.eps into our document (Note: the file extension .eps is not necessary). The figure will be centered and a caption is added just under the figure box. We also define a label in order to be able to reference the figure from the document text.

When using multiple figures in a document the above code needs to be repeated for each one of them. Let's take a look at how to define this task only once and use it in multiple places.

Defining a new command

In the previous LaTeX snippet there were 4 variables:

  • The figure position: htp.
  • The figure name.
  • The figure width: 10cm.
  • The figure caption.

We can define then a command called Figure which takes these 4 parameters in the following manner:


The command has to be defined in the document preamble or, much better, in a separate definitions file, functions.sty for instance, and then included in the preamble using \usepackage{functions} (Note: the file extension .sty is not necessary).

Once this is done, the new command can be used anywhere making it easier to include figures:

\Figure{htp}{10}{myfigure}{This is a figure example}


We have used the name of the figure file as a part of the figure label which allows us to refer to the figure from other parts of the document as \ref{fig:myfigure}. An option to think about in the future would be to add an extra parameter to allow the label to be specified externally, but this is not strictly necessary as since filenames must be unique they are good candidates to use as identifiers.

To avoid collisions it is a good practice to add prefixes to the labels: fig: for figures, sec: for sections, chp: for chapters or tab: for tables.

We have also assumed that figures are placed in a figs subfolder. This keeps document figures away from document source files.

Filed under: tools


There are no comments.