# Tag Archives: figure

## Figure with border in LaTeX

Often, figures have a white background which makes the figure border invisible on white paper. If a figure has several disconnected elements, it looks better to delimit them with a frame around figure. The adjustbox package scales, resizes, trims, rotates, and also frames LaTeX content. Conveniently, these functions can be exported to the \includegraphics command, which is what I will show below.

Load the adjustbox package with the export option to make functions available to the \includegraphics command (graphicx package).

\usepackage{graphicx}
\usepackage[export]{adjustbox}

To add a border to a figure, we simply use the frame option.

\includegraphics[width=\linewidth, frame]{figure-filename}

##### Subfigure/subfig with frame

Similarly, we can add a border to subfigures. Here, I used the subfig package, but it works with subfigure and subcaption too. See my code snippets section under figures for code examples.

## Sub-caption above subfigures and subtables

I was recently asked an interesting question about how to place a sub-caption on top of a sub-figure. By default, sub-captions are produced below sub-figures.

When using the subfigure package, the answer is reasonably easy. The package has an option to move the sub-captions on top of the figure.

\usepackage[FIGTOPCAP]{subfigure}

However, I was curious how other packages solve the problem, specifically subfig and subcaption.

Below are the solutions for all three sub-figure packages as well as the sub-tables.

##### Subfigure

We have already seen that subfigure solves the problem through a package option, which has to be typed in capital letters.

\usepackage[FIGTOPCAP]{subfigure}

\documentclass[11pt]{article}
\usepackage[FIGTOPCAP]{subfigure}
\begin{document}

\begin{figure}[ht]
\centering
\subfigure[Caption of subfigure 1]{
\rule{4cm}{3cm}
\label{fig:subfig1}
}
\subfigure[Caption of subfigure 2]{
\rule{4cm}{3cm}
\label{fig:subfig2}
}
\subfigure[Caption of subfigure 3]{
\rule{4cm}{3cm}
\label{fig:subfig3}
}
\caption[Optional caption for list of figures]{Main caption for subfigures \subref{fig:subfig1}, \subref{fig:subfig2} and \subref{fig:subfig3}}
\label{fig:subfigureExample}
\end{figure}

\end{document}

##### Subfig

Similar to subfigure, the subfig package also changes the caption position through a package option.

\usepackage[position=top]{subfig}

Alternatively, the caption position can be controlled through the captionsetup command.

\captionsetup{position=top}

This has the advantage that it can be placed anywhere within the document and similarly reset to the default.

\captionsetup{position=bottom}

\documentclass[11pt]{article}
\usepackage[position=top]{subfig}
\begin{document}
\begin{figure}[ht]
\centering
\subfloat[short for lof][Caption for sub-figure 1]{
\rule{4cm}{3cm}
\label{fig:subfig1}
}
\subfloat[short for lof][Caption for sub-figure 2]{
\rule{4cm}{3cm}
\label{fig:subfig2}
}

\subfloat[short for lof][Caption for sub-figure 3]{
\rule{4cm}{3cm}
\label{fig:subfig3}
}
\caption[Optional caption for list of figures]{Main caption for subfigures \subref{fig:subfig1}, \subref{fig:subfig2} and \subref{fig:subfig3}}
\label{fig:subfigureExample}
\end{figure}
\end{document}

##### Subcaption

The subcaption package handles positioning differently from subfigure and subfig. It defines the subfigure environment which is simply a minipage. Figures are then placed within the environment along with the caption and label. The caption can therefore be move on top of the figure simply by rearranging the commands.

\begin{subfigure}[b]{0.45\textwidth}
% Caption before figure
\subcaption[short for lof]{Caption for sub-figure}
\includegraphics[width=\linewidth]{figure-file}
\label{fig:subfig}
\end{subfigure}

\documentclass[11pt]{article}
\usepackage{subcaption}
\begin{document}
\begin{figure}
\centering
\begin{subfigure}[b]{0.45\textwidth}
\subcaption[short for lof]{Caption for sub-figure 1}
\rule{\linewidth}{3cm}
\label{fig:subfig1}
\end{subfigure}%
\begin{subfigure}[b]{0.45\textwidth}
\subcaption[short for lof]{Caption for sub-figure 2}
\rule{\linewidth}{3cm}
\label{fig:subfig2}
\end{subfigure}

\begin{subfigure}[b]{0.45\textwidth}
\subcaption[short for lof]{Caption for sub-figure 3}
\rule{\linewidth}{3cm}
\label{fig:subfig3}
\end{subfigure}
\caption[Optional caption for list of figures]{Main caption for subfigures \subref{fig:subfig1}, \subref{fig:subfig2} and \subref{fig:subfig3}}
\end{figure}
\end{document}

##### Table

Similar solutions exist for placement of sub-table captions above or below the table.

% Subfigure package
\usepackage[TABTOPCAP]{subfigure} % above
\usepackage[TABBOTCAP]{subfigure} % below (default)

% Subfig package
\usepackage{subfig}
\captionsetup[subtable]{position=top}

% Subcaption package
\begin{subtable}[b]{0.45\textwidth}
% Caption before figure
\subcaption[short for lof]{Caption for sub-table}
...
\label{tab:subtab}
\end{subtable}

## Rotate an image, table or paragraph in LaTeX

The rotating package provides easy-to-use functionality to rotate content. The float environments sidewaystable and sidewaysfigure introduce landscape tables and figures, respectively. The package automatically takes care of the rotation direction for twoside documents. Besides 90 degrees rotation, the package also provides a command and environment to rotate content at an arbitrary angle.

##### Sidewaysfigure example

The easiest way to take full advantage of the page and position a figure (or table) in landscape-form is through the rotating package.

\documentclass[11pt]{article}
\usepackage{rotating, graphicx}
\begin{document}
\begin{sidewaysfigure}
\includegraphics[width=\textwidth]{capsules}
\caption{Result of a long day  at work.}
\end{sidewaysfigure}
\end{document}

I manually rotated the page to better fit here. Sidewaysfigure will place the figure on a separate page, as will sidewaystable.

##### Arbitrary angle text example

The command turn allows rotation at an arbitrary angle in degrees. Here is a rather useless example, but you get the idea:

\documentclass[11pt]{article}
\usepackage{blindtext, rotating}
\begin{document}
\begin{turn}{45}
\begin{minipage}{\linewidth}
\blindtext
\end{minipage}
\end{turn}
\blindtext
\end{document}

I use the minipage environment to limit the text horizontally. Otherwise, the entire paragraph is printed on a single line. The picture below is a snapshot of the output.

Did you come across an awesome package or would like me to write about a particular topic? Get in touch.

## Cleveref, a clever way to reference in LaTeX

Using standard cross-referencing in LaTeX only produces the label number, a name describing the label such as figure, chapter or equation has to be added manually. The cleveref package overcomes this limitation by automatically producing the label name and number. It further allows cross-referencing ranges of labels and multiple labels of the same or different kinds, including auto-sorting and compression of labels.

##### Basic cross-reference command

Cleveref implements \cref for basic cross-referencing. The command is used in the same way as the standard \ref command. Besides the label number it also produces the reference kind.

Warning: cleverref has to be loaded after hyperref!

Here is an example:

\documentclass[11pt]{article}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{cleveref}
\begin{document}

\begin{align}
y&=a_1x+b_1\label{eqn:1}
\end{align}

\noindent
Standard equation reference (\textbackslash ref): \ref{eqn:1}\\
Cleveref equation reference (\textbackslash cref): \cref{eqn:1}

\begin{figure}[ht]\centering\rule{0.5\linewidth}{0.1\linewidth}\caption{First figure}\label{fig:1}\end{figure}

\noindent
Standard figure reference (\textbackslash ref): \ref{fig:1}\\
Cleveref figure reference (\textbackslash cref): \cref{fig:1}

\end{document}

##### Multiple labels (sort and compress)

To cross-reference multiple labels of the same or different kinds, the \cref command is used. Labels are separated by commas without white-space (\cref{ref1,ref2,etc.}). For a range of the same label kind, the command \crefrange{first}{last} is available.

\documentclass[11pt]{article}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{cleveref}

\begin{document}

\begin{align}
y&=a_1x+b_1\label{eqn:1}\\
y&=a_2x+b_2\label{eqn:2}\\
y&=a_3x+b_3\label{eqn:3}\\
y&=a_4x+b_4\label{eqn:4}
\end{align}

\noindent
Range example: \crefrange{eqn:1}{eqn:4}

\begin{figure}[ht]\centering\rule{0.5\linewidth}{0.1\linewidth}\caption{First figure}\label{fig:1}\end{figure}

\noindent
Mixed references example: \cref{eqn:1,eqn:3,eqn:4,fig:1}

\end{document}

##### Capitalize at beginning of sentence

By default, label names are produced with a small initial letter. To capitalize the first letter at the beginning of a sentence, use \Cref and \Crefrange instead.

For capitalization of all label names throughout the document, load the package with the capitalise option.

\usepackage[capitalise]{cleveref}

##### Full label names

If you prefer to use the full label name rather than abbreviations such as fig. or eq., load the package with the noabbrev option:

\usepackage[noabbrev]{cleveref}

##### Clickable references with hyperref

The cleveref package is fully compatible with hyperref (package manual). It is important to load the cleveref package last, after hyperref.

% Preamble
\usepackage{...} % other packages
\usepackage{hyperref}
\usepackage{cleveref}

\begin{document}
...

##### Other features of the package

The cleveref package offers a lot more, including:

• Customization of labels
• Name-only references
• Page number of label
• and more…

See the package documentation for more details.

##### Alternative packages

There are a number of packages implementing similar features. According to the documentation, cleveref is among the most extensive in terms of functionality and flexibility. However, through a recently published post on LaTeX Alive I learnt that the refstyle package is a valid alternative to cleveref and I’ll definitely give it a try.

## Side-by-side content in beamer presentations

There are two ways (and possibly more) to place content side-by-side in a beamer presentation, the columns and the minipage environments. The first is a beamer-specific environment and is therefore only available in a beamer presentation. Whereas the latter has other applications and is available in all document-classes.

##### General considerations

In any LaTeX document, there is a predefined width available for text, \textwidth. In order to place content side-by-side, this width has to be split in such a way that the total width of all elements does not exceed \textwidth. Otherwise, LaTeX will automatically break the line and place elements on top of each other, which is usually not desired. The value \textwidth can be used to define the width of a column or minipage. For example, 0.33\textwidth takes a third of width of a page available for content. LaTeX also adds a small horizontal space between elements. Therefore, in order to split a page into three equal parts, 0.3\textwidth might be a more reasonable number. If required, one can add more horizontal white-space between two elements using \quad or \qquad.

##### The columns environment

The columns environment is only available in the beamer document-class and might therefore be lesser known.

Basic command structure:

\begin{columns}
\begin{column}{0.48\textwidth}
%Content
\end{column}
\begin{column}{0.48\textwidth}
%Content
\end{column}
\end{columns}

And here is a complete minimal working example:

\documentclass{beamer}
\begin{document}
\begin{frame}{The columns environment}
\begin{columns}
\begin{column}{0.47\textwidth}
\begin{itemize}
\item First item
\item Second item
\item Third item
\end{itemize}
\end{column}
\begin{column}{0.5\textwidth}
\rule{\textwidth}{0.75\textwidth}
\end{column}
\end{columns}
\end{frame}
\end{document}

##### The minipage environment

I wrote an article on the minipage environment quite some time ago. In beamer, the usage is not different.

The command is used as follows:

\begin{minipage}{0.45\textwidth}
%Content
\end{minipage}

Below is a complete minimal working example:

\documentclass{beamer}
\begin{document}
\begin{frame}{The minipage environment}
\begin{minipage}{0.47\textwidth}
\begin{itemize}
\item First item
\item Second item
\item Third item
\end{itemize}
\end{minipage}
\begin{minipage}{0.5\textwidth}
\rule{\textwidth}{0.75\textwidth}
\end{minipage}
\end{frame}
\end{document}

##### Final note

Even though there are differences, I don’t know of any advantage of one method over the other when placing content side-by-side. However, I suggest choosing one environment and sticking to it throughout a presentation.

## Keeping things organized in large documents

In large project such as dissertations or even books, it is important and necessary to keep the content organized. One way is to split a document, by chapter for example, and then load the parts using input or include. The catchfilebetweentags package offers a more flexible way to organize content. It let’s you store chunks of code in another file. The code chunks don’t have to be ordered, as tags are used for identification. This way, you can store equations, tables or figures apart from text, making content more manageable.

In the following example, I will use two tex-files, a main document, main.tex, and a document containing all figures, figures.tex.

Main document

\documentclass[11pt]{article}

}
\begin{document}

\end{document}

First the package is loaded. Next, we define a new macro for figures that takes one argument, the tag ID, being the tag name. Inside the macro, we call another macro, ExecuteMetaData defined by the package, to load a code chunk from file: figures.tex. The package will then find the tag with the same name as the ID and replace \loadFigure{tagID} by the actual chunk.

Code chunks file

The code chunks can be exported in any order to a text file (in my case figures.tex). In fact, any text file will do. Important is that the chunks are delimited by tags with same ID used to load the chunk in the main file. Also notice the % symbol in from of the tags and the * inside the opening tag.

%<*tagID>
...LaTeX code...
%</tagID>

To complete the example above, I created figures.tex, containing two dummy figures and placed the file into the same directory as the main document, main.tex. However, you could use any directory, just make sure to change the filename by adding the path in the main file, i.e. \ExecuteMetaData[path/to/file]{#1}.

%Figure file: figures.tex

%<*fig:02>
\begin{figure}[ht]
\begin{center}
\rule{0.4\textwidth}{0.3\textwidth}
\caption{My second figure}
\label{fig:01}
\end{center}
\end{figure}
%</fig:02>

%<*fig:01>
\begin{figure}[ht]
\begin{center}
\rule{0.3\textwidth}{0.4\textwidth}
\caption{My first figure.}
\label{fig:01}
\end{center}
\end{figure}
%</fig:01>

The \rule{}{} command used in the example is just a figure placeholder and will produce a black box of the size given.

Many thanks to Giacomo Drago who pointed the package out to me and from where I copied the macro code.

## Stop loosing track of labels by displaying them in the PDF

Sometimes it is hard to keep track of labels, particularly in large documents with many figures, tables or equations. Unless you remember all label names by heart, you will likely scroll up and down till you find the particular position in the text where the label is defined. The showlabels package provides a convenient way for keeping track of label names. It displays them in the PDF next to the text element it was defined for.

Usage is straight forward, it is sufficient to load the package in the preamble of the document:

\usepackage{showlabels}

By default, labels are printed to the outer margin. Options are available to display labels in the inner/left/right margin or inline. See the package documentation for more details.

Furthermore, you can print arguments to pretty much any command. This is particularly useful for cite. See below for an example.

\showlabels{cite}

Obviously, this is not something you want in the final document. Either just delete all the code related to the package or better, use the final option to mute it:

\usepackage[final]{showlabels}

Example: figure

Example: equation

Example: enumerate

Example: cite

\documentclass{article}
\usepackage{showlabels, bibentry}
\usepackage{blindtext}
\showlabels{cite}
\begin{filecontents}{publication.bib}
@article{lamport1986latex,
title={LaTEX: User's Guide \&amp; Reference Manual},
author={Lamport, L.},
year={1986},
}
\end{filecontents}
\begin{document}
\blindtext
\section{Figure}
\begin{figure}[ht]
\centering
\rule{4cm}{3cm}
\caption{default}
\label{fig:default}
\end{figure}
\section{Equation}
$$\label{eq:default}f(x)=ax^2+bx+c$$
\section{Enumerate}
\begin{enumerate}
\item First item\label{itm:first}
\item Second item\label{itm:second}
\end{enumerate}
\section{Citation}
\cite{lamport1986latex}\\
\nobibliography{publication}
\end{document}

First seen here.

## Cropping the output file to its content in LaTeX

The documentclass options a4paper or letterpaper are certainly not the right choices when creating a set of equations or vector graphics using TiKZ for embedding in another document or standalone usage. Ideally, the output file is automatically set to fit its content, possibly with some whitespace around it.

The following post describes two possible ways:

##### The standalone documentclass

Really simple, instead of using a standard documentclass such as article or report, use standalone.

A simple example

\documentclass[varwidth=true, border=10pt, convert={size=640x}]{standalone}
\usepackage{blindtext}
\begin{document}
\blindtext
\end{document}

I don’t show the output here. Its a png-file showing some blind-text.

Options used

• varwidth: Uses \linewidth as document-width. If the package is loaded without the option, all line-breaks are ignored.
• border: Adds some whitespace around the content.
• convert: Converts the output to png. Convert itself takes arguments such as size used in the example or the output image format extension. Loading the package without the option creates the output in pdf format. Standalone uses Image Magick (or Ghostscript) for conversion, different image formats are available. Please see the documentation for more information.

A full list of options is provided in the standalone bundle documentation. Interestingly, the background of the figure is transparent, which may not always be desirable. As the name already suggests, standalone is a bundle and has a lot more to offer than what is shown here. However, I hope this covers the most common usage.

A more fancy example

The code was taken from A calendar of circles on TeXample.net. Again, the pdf output was converted to png using the standalone documentclass option convert in order to be able to embed it here.

TeXample.net has a great collection of pgf/TiKZ graphics. Go check it out if you haven’t done so yet!

A graphic I recently created using the standalone documentclass and the adjustbox package:

Here is the pdf, perfectly scalable.

##### The preview package

Preview is a package rather than a document-class like standalone. Therefore, it has to be loaded in the preamble. Here is the same example given for standalone above:

\documentclass[11pt]{article}
\usepackage{blindtext}
\usepackage[active, tightpage]{preview}
\setlength\PreviewBorder{10pt}%
\begin{document}
\begin{preview}
\blindtext
\end{preview}
\end{document}

Using PDFs will not affect the quality of the font and is perfectly scalable. I “png” here for visualization purposes. The quality is reasonable, but the figure is not scalable which is why it looks so bad here.

A few notes on the code

• active: If not used, the package won’t do anything.
• \PreviewBorder: Controls the whitespace around the content. Is set through \setlength, as shown in the example.
• preview-environment: An easy way to tell preview what to include. Another way would be to use an existing environment such as center by adding: \PreviewEnvironment{center} to the preamble and using \begin{center}...\end{center}.

See the documentation for more details.

Under Linux or Mac OS X if Ghostscript is installed, use the following command in the terminal to convert pdf to png:

gs -sDEVICE=png16m -dTextAlphaBits=4 -r300 -dGraphicsAlphaBits=4 -dSAFER -q -dNOPAUSE -sOutputFile=⟨outputfile⟩%d.png ⟨inputfile⟩.pdf

I recently wrote about cropping figures using the graphics bundle. Here is another fancy way to get more out of your figures.

The fancybox package implements commands for various boxes such as a box with round corners. The command shadowbox creates a black box with a shadow. It works with normal text, in math mode as well as with floats such as the figure environment.

To add a shadow to a figure, we need two things. First we load the fancybox package. Next, we add a shadowbox around includegraphics. Note, the box encompasses only the actual content and not the entire float.

\usepackage{fancybox, graphicx}
...
\begin{figure}[ht]
\end{figure}

As simple as that.

And here is the result with a minimal working example below.

\documentclass{article}
\usepackage{fancybox}
\begin{document}
\begin{figure}[ht]
\centering
\caption{Phantom figure}
\end{figure}
\tiny\hfill Created by http://texblog.org
\end{document}

A few clarifications on the minimal working example

• \rule{width}{height} adds a black box as a placeholder for a figure.
• \phantom{argument} adds an invisible box of the size of its argument.
• Again, make sure the box only contains the actual content and not the float.

## Wide figure/table in a twocolumn/multi-column document

The floating environments figure* and table* allow adding wide, single-column tables or figures in a two- or multicolumn document.

Here is an example.

##### Wide figure in a 3-column-document

The example makes use of the multicol package. For two columns, it is sufficient to use the documentclass-option twocolumn. The starred version of figure, figure*, and table, table* are floating environments. Therefore, LaTeX will place the figure only on the second page, rather than at the beginning of the document.

\documentclass[11pt]{article}
\usepackage{multicol, blindtext}
\begin{document}
\begin{multicols}{3}
\begin{figure*}[ht]
\centering
\rule{\linewidth}{3cm}
\caption{Wide single column figure in a twocolumn document.}
\end{figure*}
\Blindtext
\end{multicols}
\end{document}

It works exactly the same way for tables.

##### Wide table in a 2-column-document

\documentclass[twocolumn]{article}
\usepackage{blindtext}
\begin{document}
\begin{table*}[ht]
\caption{Wide single-column table in a twocolumn document.}
\centering
\begin{tabular}{p{0.25\linewidth}p{0.25\linewidth}p{0.25\linewidth}}
\hline
column 1 & column 2 & column 3\\
\hline
cell 1 & cell 2 & cell 3\\
cell 1 & cell 2 & cell 3\\
\hline
\end{tabular}
\end{table*}
\Blindtext\Blindtext
\end{document}

##### Side-by-side figures with subfig

It works exactly the same for side-by-side figures and tables (subfig package). See my post on that topic for more details. In this example, the dblfloatfix package is loaded. It “fixes” an issue with the floating environment and allows placing figures and tables at the bottom of a page.

\documentclass[twocolumn]{article}
\usepackage{blindtext, subfig}
\usepackage{dblfloatfix} % fix for bottom-placement of figure
\setlength{\columnseprule}{0.5pt}
\begin{document}
\begin{figure*}[hb]
\centering
\subfloat[][]{
\rule{0.45\linewidth}{3cm}
}
\subfloat[][]{
\rule{0.45\linewidth}{3cm}
}
\caption{Wide single column figure in a twocolumn document.}
\end{figure*}
\Blindtext\Blindtext
\end{document}

By default, figures and table will always be placed either at the top of a page or occupy a whole page. In the last example, we saw that it is possible to “fix” the float issue using the dblfloatfix package. However, there is no way to place the figure in the middle of the page, using the option [b].
Mixing “starred” and “non-starred” figures/tables is possible. For LaTeX to display the floats in the right order, load the fixltx2e package.
\setlength{\columnsep}{2cm}
\setlength{\columnseprule}{0.5pt}