# Tag Archives: figure

## 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.

You can change the horizontal space between columns through:

\setlength{\columnsep}{2cm}

The following code adds a separation line between columns:

\setlength{\columnseprule}{0.5pt}

## Crop figures with includegraphics

Imagine having a beautiful picture, but the subject is very small or not centered. What if you want to place several graphs side-by-side with subfig, but all or some of the graphs have a white border taking up a lot of space.

So how to trim pictures and eliminate unwanted margins of graphs?

The graphics bundle provides a way to crop an image using the trim, clip options of the includegraphics command.

\usepackage{graphicx}
...
\begin{figure}[htbp]
\begin{center}
\includegraphics[trim=left bottom right top, clip]{file}
\caption{default}
\label{default}
\end{center}
\end{figure}

Unless you know exactly how much to crop, you will probably have to try a few times, until you get the numbers right. Make sure you don’t forget clip, since trim alone won’t work. The default units are big points (bp). However, any unit available in LaTeX can be used. See here for more information on units.

Finally, using negative values adds white space to a figure, doing exactly the opposite of cropping.

The graphics bundle user guide has more details and a comprehensive list of options available.

Here is an example:

\documentclass[11pt]{article}
\usepackage{graphicx}
\begin{document}
\begin{figure}[h!t]
\begin{center}
\includegraphics[width=\textwidth]{crab}
\end{center}
\label{fig:orig}
\end{figure}
\begin{figure}[h!b]
\begin{center}
\includegraphics[trim=1200 400 1500 1500,clip,width=\textwidth]{crab}
\end{center}
\label{fig:crop}
\end{figure}
\end{document}

Original and includegraphics trimmed figure.

In large documents, you may end up with a pretty long list of figures or tables. In this post, I will show how to nicely structure these lists by adding subtitles. The whole thing turned out to be more tricky than I first thought, but more on that later. The my examples, I will show how to organize the list of figures by chapters. However, the code can be adapted and extended with little effort, including doing the same for the list of tables, organizing the lists by different levels (part, section) for the various documentclasses, the actual subtitle format (with/without name, page number), etc.

The main idea is to add a line to the list of figures whenever a new chapter is created. That’s relatively straight forward, we extend the chapter command by defining a custom command.

\newcommand{\newchapter}[1]{%
\chapter{#1}
Chapter \thechapter: #1 \vspace{10pt}
}
}

The lines highlighted add a full entry to the list of figures. In order to omit the page number, use addtocontents as follows instead.

\addtocontents{lof}{\contentsline{chapter}{%
Chapter \thechapter \vspace{10pt}}{}
}

This is all great and easy. The problem starts, however, when individual chapters have no figures. Then, the subtitle will still be printed, however, that there is no content. This is not exactly what we want. Therefore, we add a condition on when to print the subtitle and when not. The etoolbox package comes in handy here, it provides “if-then-else-like” statements. Here is the documentation. Briefly, whenever a new chapter starts, we set the parameter newchap to true. The subtitle is printed along with the first caption added to the list of figures. Therefore, if a chapter has no figure, the subtitle will not show up in the list.

First, we define the boolean parameter newchap:

\providebool{newchap}

Next, we define an alternative chapter command newchapter. This time, however, instead of directly adding the subtitle to the list, we only set the boolean parameter to true:

\newcommand{\newchapter}[1]{%
\chapter{#1}
\global\setbool{newchap}{true}
}

And finally, we redefine the caption command. The additional definition of shortcaption is necessary to support the optional caption argument, the alternative short caption for the list of figures.

\let\oldcaption\caption
\renewcommand{\caption}[2][\shortcaption]{%
\def\shortcaption{#2}
\ifbool{newchap}{%
Chapter \thechapter \vspace{10pt}
}{}}}{}
\global\boolfalse{newchap}
\oldcaption[#1]{#2}
}

If you never use the optional argument of the chapter command (chapter[alternative toc name]{real chapter name}) throughout your document, this is basically it, we are done.

In case you use the optional augment, however, we are not quite done yet, since we redefined chapter and by doing so omitted some of the functionality. We can fix this issue by redefining chapter in a different way, similarly to what we did for caption which brings additional advantages. On one hand, the code becomes more consistent and on the other hand, you won’t have to change chapter to newchapter throughout your document, since we just redefine the command rather than replace it. And here is the code:

\makeatletter
\newcommand{\saved@chapter}{}
\let\saved@chapter\chapter
\renewcommand{\chapter}{%
\@ifstar {\saved@chapter*}{\@dblarg\my@chapter}%
}
\newcommand*{\my@chapter}[2][]{%
\saved@chapter[#1]{#2}%
\global\setbool{newchap}{true}
}
\makeatother

I got this piece of code from this google group.

And here is what the final result looks like. Pretty cool, huh :-).

List of figures with subtitles

The whole story only makes sense and works with numbered chapters, (i.e. when using the starred version: \chapter*{} you may run into problems or get undesired results, but you would have to try).

I am pretty sure there is an alternative, maybe simpler way to do the same thing. Maybe the tocloft package has a solution. Feel free to drop a comment and let me know about it. Thanks.