LaTeX/Floats, Figures and Captions


The previous chapter introduced importing graphics. However, just having a picture stuck in between paragraphs does not look professional. To start with, we want a way of adding captions, and to be able to cross-reference. What we need is a way of defining figures. It would also be good if LaTeX could apply principles similar to when it arranges text to look its best to arrange pictures as well. This is where floats come into play.

LaTeX

Getting Started
  1. Introduction
  2. Installation
  3. Installing Extra Packages
  4. Basics
  5. How to get help

Common Elements

  1. Document Structure
  2. Text Formatting
  3. Paragraph Formatting
  4. Colors
  5. Fonts
  6. List Structures
  7. Special Characters
  8. Internationalization
  9. Rotations
  10. Tables
  11. Title creation
  12. Page Layout
  13. Customizing Page Headers and Footers‎
  14. Importing Graphics
  15. Floats, Figures and Captions
  16. Footnotes and Margin Notes
  17. Hyperlinks
  18. Labels and Cross-referencing
  19. Initials

Mechanics

  1. Errors and Warnings
  2. Lengths
  3. Counters
  4. Boxes
  5. Rules and Struts

Technical Text

  1. Mathematics
  2. Advanced Mathematics
  3. Theorems
  4. Chemical Graphics
  5. Algorithms
  6. Source Code Listings
  7. Linguistics

Special Pages

  1. Indexing
  2. Glossary
  3. Bibliography Management
  4. More Bibliographies

Special Documents

  1. Scientific Reports (Bachelor Report, Master Thesis, Dissertation)
  2. Letters
  3. Presentations
  4. Teacher's Corner
  5. Curriculum Vitae
  6. Academic Journals (MLA, APA, etc.)

Creating Graphics

  1. Introducing Procedural Graphics
  2. MetaPost
  3. Picture
  4. PGF/TikZ
  5. PSTricks
  6. Xy-pic
  7. Creating 3D graphics

Programming

  1. Macros
  2. Plain TeX
  3. Creating Packages
  4. Creating Package Documentation
  5. Themes

Miscellaneous

  1. Modular Documents
  2. Collaborative Writing of LaTeX Documents
  3. Export To Other Formats

Help and Recommendations

  1. FAQ
  2. Tips and Tricks

Appendices

  1. Authors
  2. Links
  3. Package Reference
  4. Sample LaTeX documents
  5. Index
  6. Command Glossary

edit this boxedit the TOC

Floats

edit

Floats are containers for things in a document that cannot be broken over a page. LaTeX by default recognizes "table" and "figure" floats, but you can define new ones of your own (see Custom floats below). Floats are there to deal with the problem of the object that won't fit on the present page and to help when you really don't want the object here just now.

Floats are not part of the normal stream of text, but separate entities, positioned in a part of the page to themselves (top, middle, bottom, left, right, or wherever the designer specifies). They always have a caption describing them and they are always numbered so they can be referred to from elsewhere in the text. LaTeX automatically floats Tables and Figures, depending on how much space is left on the page at the point that they are processed. If there is not enough room on the current page, the float is moved to the top of the next page. This can be changed by moving the Table or Figure definition to an earlier or later point in the text, or by adjusting some of the parameters which control automatic floating.

Authors sometimes have many floats occurring in rapid succession, which raises the problem of how they are supposed to fit on the page and still leave room for text. In this case, LaTeX stacks them all up and prints them together if possible, or leaves them to the end of the chapter in protest. The skill is to space them out within your text so that they intrude neither on the thread of your argument or discussion nor on the visual balance of the typeset pages.

As with various other entities, there exist limitations on the number of unprocessed (placed) floats in line. LaTeX by default can cope with maximum 18 floats and a symptomatic error is:

! LaTeX Error: Too many unprocessed floats.

The morefloats package lifts this limit.

Figures

edit

To create a figure that floats, use the figure environment.

\begin{figure}[placement specifier]
... figure contents ...
\end{figure}

The previous section mentioned how floats are used to allow LaTeX to handle figures while maintaining the best possible presentation. However, there may be times when you disagree, and a typical example is with its positioning of figures. The placement specifier parameter exists as a compromise, and its purpose is to give the author a greater degree of control over where certain floats are placed.

Specifier Permission
h Place the float here, i.e., approximately at the same point it occurs in the source text (however, not exactly at the spot)
t Position at the top of the page.
b Position at the bottom of the page.
p Put on a special page for floats only.
! Override internal parameters LaTeX uses for determining "good" float positions.
H Places the float at precisely the location in the LaTeX code. Requires the float package,[1] i.e., \usepackage{float}.

What you do with these placement permissions is to list which of the options you wish to make available to LaTeX. These are simply possibilities, and LaTeX will decide when typesetting your document which of your supplied specifiers it thinks is best. Frank Mittelbach describes the algorithm[2]:

  • If a float is encountered, LaTeX attempts to place it immediately according to its rules (detailed later)
    • If this succeeds, the float is placed and that decision is never changed;
    • If this does not succeed, then LaTeX places the float into a holding queue to be reconsidered when the next page is started (but not earlier).
  • Once a page has finished, LaTeX examines this holding queue and tries to empty it as best as possible. For this, it will first try to generate as many float pages as possible (in the hope of getting floats off the queue). Once this possibility is exhausted, it will next try to place the remaining floats into top and bottom areas. It looks at all the remaining floats and either places them or defers them to a later page (i.e., re-adding them to the holding queue once more).
  • After that, it starts processing document material for this page. In the process, it may encounter further floats.
  • If the end of the document has been reached or if a \clearpage is encountered, LaTeX starts a new page, relaxes all restrictive float conditions, and outputs all floats in the holding queue by placing them on float page(s).

In some special cases, LaTeX won't follow these positioning parameters and additional commands will be necessary, for example, if one needs to specify an alignment other than centered for a float that sits alone in one page[3].

Use \listoffigures to add a list of the figures in the beginning of the document. To change the name used in the caption from Figure to Example, use \renewcommand{\figurename}{Example} in the figure contents. See the New commands section for more information on this.

Figures with borders

edit

It's possible to get a thin border around all figures. You have to write the following once at the beginning of the document:

\usepackage{float}
\floatstyle{boxed} 
\restylefloat{figure}

The border will not include the caption.

Tables

edit

Floating tables are covered in a separate chapter. Let's give a quick reminder here. The tabular environment that was used to construct the tables is not a float by default. Therefore, for tables you wish to float, wrap the tabular environment within a table environment, like this:

\begin{table}
  \begin{tabular}{...}
  ... table data ...
  \end{tabular}
\end{table}

You may feel that it is a bit long-winded, but such distinctions are necessary, because you may not want all tables to be treated as a float.

Use \listoftables to add a list of the tables in the beginning of the document.

Keeping floats in their place

edit

The placeins[1] package provides the command \FloatBarrier, which can be used to prevent floats from being moved over it. This can, e.g., be useful at the beginning of each section. The package even provides an option to change the definition of \section to automatically include a \FloatBarrier. This can be set by loading the package with the option [section] (\usepackage[section]{placeins}). \FloatBarrier may also be useful to prevent floats intruding on lists created using itemize or enumerate.

The flafter package can be used to force floats to appear after they are defined, and the endfloat[2] package can be used to place all floats at the end of a document.

The float[3] package provides the H option to floating environments, which completely stops them from floating.

Package caption[4] provides the command \captionof{<type>}{<caption text>} that lets you typeset a caption without a floating environment. You have the full and absolute control about the placement of your figures and captions.

Captions

edit

It is always good practice to add a caption to any figure or table. Fortunately, this is very simple in LaTeX. All you need to do is use the \caption{''text''} command within the float environment. LaTeX will automatically keep track of the numbering of figures, so you do not need to include this within the caption text.

The location of the caption is traditionally underneath the float. However, it is up to you to, therefore, insert the caption command after the actual contents of the float (but still within the environment). If you place it before, then the caption will appear above the float. Try out the following example to demonstrate this effect:

\documentclass[a4paper,12pt]{article}

\usepackage[english]{babel}
\usepackage{graphicx}

\begin{document}

\begin{figure}
  \caption{A picture of a gull.}
  \centering
    \includegraphics[width=0.5\textwidth]{gull}
\end{figure}

\begin{figure}
  \centering
    \reflectbox{%
      \includegraphics[width=0.5\textwidth]{gull}}
  \caption{A picture of the same gull
           looking the other way!}
\end{figure}

\begin{table}
  \centering
    \begin{tabular}{| l c r |}
    \hline
    1 & 2 & 3 \\
    4 & 5 & 6 \\
    7 & 8 & 9 \\
    \hline
    \end{tabular}
  \caption{A simple table}
\end{table}

Notice how the tables and figures
have independent counters.

\end{document}
 

Note that the command \reflectbox{...} flips its content horizontally.

Side captions

edit

It is sometimes desirable to have a caption appear on the side of a float, rather than above or below. The sidecap package can be used to place a caption beside a figure or table. The following example demonstrates this for a figure by using a SCfigure environment in place of the figure environment. The floatrow package is newer and has more capabilities.

\documentclass{article}

\usepackage{graphicx}
\usepackage{sidecap}

\begin{document}

\begin{SCfigure}
  \centering
  \caption{ ... caption text ... }
  \includegraphics[width=0.3\textwidth]%
    {Giraffe_picture}% picture filename
\end{SCfigure}

\end{document}

 

Unnumbered captions

edit

In some types of documents (such as presentations), it may not be desirable for figure captions to start with Figure:. This is easy to suppress by just placing the caption text in the figure environment, without enclosing it in a caption. This however means that there is no caption available for inclusion in a list of figures.

Caption Setup Rename

edit

In case you want to rename your table caption from "Table" to something else, you can use the \captionsetup command. For example,

\usepackage{caption}
\captionsetup[table]{name=New Table Name}

\usepackage{caption} \captionsetup[table] {name=New Table Name}

Lists of figures and tables

edit

Captions can be listed at the beginning of a paper or report in a "List of Tables" or a "List of Figures" section by using the \listoftables or \listoffigures commands, respectively. The caption used for each figure will appear in these lists, along with the figure numbers, and page numbers that they appear on.

The \caption command also has an optional parameter, \caption[''short'']{''long''} which is used for the List of Tables or List of Figures. Typically the short description is for the caption listing, and the long description will be placed beside the figure or table. This is particularly useful if the caption is long, and only a "one-liner" is desired in the figure/table listing. Here is an example of this usage:

\documentclass[12pt,]{article}
\usepackage{graphicx}
\newcommand{\species}[1]{\textit{#1} sp.}
\begin{document}

\listoffigures
\section{Introduction}

\begin{figure}
	\centering
	\includegraphics[width=4in]{gecko}
	\caption[Close up of \species{Hemidactylus}]
	{Close up of \species{Hemidactylus}, which is part the genus of the gecko family. It is the second most speciose genus in the family.}
\end{figure}

\end{document}

 

Labels and cross-referencing

edit

Labels and cross-references work fairly similarly to the general case - see the Labels and Cross-referencing section for more information.

If the label picks up the section or list number instead of the figure number, put the label inside the caption to ensure correct numbering. If you get an error when the label is inside the caption, use \protect in front of the \label command.

Wrapping text around figures

edit

An author may prefer that some floats do not break the flow of text, but instead allow text to wrap around it. (Obviously, this effect only looks decent when the figure in question is significantly narrower than the text width.)

A word of warning: Wrapping figures in LaTeX will require a lot of manual adjustment of your document. There are several packages available for the task, but none of them work perfectly. Before you make the choice of including figures with text wrapping in your document, make sure you have considered all the options. For example, you could use a layout with two columns for your documents and have no text-wrapping at all.

Anyway, we will look at the package wrapfig. Note that wrapfig may not come with the default installation of LaTeX; you might need to install additional packages. Noted also, wrapfig is incompatible with the enumerate and itemize environments

To use wrapfig, you must first add this to the preamble:

\usepackage{wrapfig}

This then gives you access to:

\begin{wrapfigure}[lineheight]{position}[overhang]{width}

The lineheight is expressed as the number of lines of text the figure spans. LaTeX will automatically calculate the value if this option is left blank but this can result in figures that look ugly (with too much spacing). The LaTeX calculation is manually overridden by entering the number of lines you would like the figure to span. This option can't be entered in pt, mm, etc...

There are overall eight possible positioning targets:

r R right side of the text
l L left side of the text
i I inside edge–near the binding (in a twoside document)
o O outside edge–far from the binding

The uppercase-character allows the figure to float, while the lowercase version means "exactly here". [4]

The overhang of the figure can be manually set using the overhang option in pt, cm, etc...

The width is, of course, the width of the figure. An example:

\begin{wrapfigure}{r}{0.5\textwidth}
  \begin{center}
    \includegraphics[width=0.48\textwidth]{gull}
  \end{center}
  \caption{A gull}
\end{wrapfigure}
 

You can also allow LaTeX to assign a width to the wrap by setting the width to 0pt: \begin{wrapfigure}{l}{0pt}

Note that we have specified a size for both the wrapfigure environment and the image we have included. We did it in terms of the text width: it is always better to use relative sizes in LaTeX, let LaTeX do the work for you! The "wrap" is slightly bigger than the picture, so the compiler will not return any strange warning and you will have a small white frame between the image and the surrounding text. You can change it to get a better result, but if you don't keep the image smaller than the "wrap", you will see the image over the text.

The wrapfig package can also be used with user-defined floats with float package. See below in the section on custom floats.

Tip for figures with too much white space

edit

You can use intextsep parameter to control additional space above and below the figure: \setlength\intextsep{0pt}

To control the horizontal space between the image and the text, use the columnsep parameter.

It happens that you'll generate figures with too much (or too little) white space on the top or bottom. In such a case, you can simply make use of the optional argument [lineheight]. It specifies the height of the figure in the number of lines of text. Also remember that the environment center adds some extra white space at its top and bottom; consider using the command \centering instead.

Another possibility is adding space within the float using the \vspace{...} command. The argument is the size of the space you want to add, you can use any unit you want, including pt, mm, in, etc. If you provide a negative argument, it will add a negative space, thus removing some white space. Using \vspace tends to move the caption relative to the float while the [lineheight] argument does not. Here is an example using the \vspace command, the code is exactly the one of the previous cases, we just added some negative vertical spaces to shrink everything up:

\begin{wrapfigure}{r}{0.5\textwidth}
  \vspace{-20pt}
  \begin{center}
    \includegraphics[width=0.48\textwidth]{gull}
  \end{center}
  \vspace{-20pt}
  \caption{A gull}
  \vspace{-10pt}
\end{wrapfigure}
 
336

In this case, it may look too shrunk, but you can manage spaces the way you like. In general, it is best not to add any space at all: let LaTeX do the formatting work!

(In this case, the problem is the use of \begin{center} to center the image. The center environment adds extra space that can be avoided if \centering is used instead.)

Alternatively, you might use the picins package instead of the wrapfig package which produces a correct version without the excess white space out of the box without any hand-tuning.

There is also an alternative to wrapfig: the package floatflt [5].

To remove the white space from a figure once for all, one should refer to the program pdfcrop, included in most TeX installations.

Subfloats

edit

A useful extension is the subcaption[6] package, which uses subfloats within a single float. The subfig package (subfigure package is deprecated[5]) is a useful alternative when used in conjunction with LaTeX templates (i.e. templates for journals from Springer and IOP, IEEETran and ACM SIG) that are not compatible with subcaption. These packages give the author the ability to have subfigures within figures, or subtables within table floats. Subfloats have their own caption, and an optional global caption. An example will best illustrate the usage of the subcaption package:

\usepackage{graphicx}
\usepackage{subcaption}

\begin{figure}
    \centering
    \begin{subfigure}[b]{0.3\textwidth}
        \includegraphics[width=\textwidth]{gull}
        \caption{A gull}
        \label{fig:gull}
    \end{subfigure}
    ~ %add desired spacing between images, e. g. ~, \quad, \qquad, \hfill etc. 
      %(or a blank line to force the subfigure onto a new line)
    \begin{subfigure}[b]{0.3\textwidth}
        \includegraphics[width=\textwidth]{tiger}
        \caption{A tiger}
        \label{fig:tiger}
    \end{subfigure}
    ~ %add desired spacing between images, e. g. ~, \quad, \qquad, \hfill etc. 
    %(or a blank line to force the subfigure onto a new line)
    \begin{subfigure}[b]{0.3\textwidth}
        \includegraphics[width=\textwidth]{mouse}
        \caption{A mouse}
        \label{fig:mouse}
    \end{subfigure}
    \caption{Pictures of animals}\label{fig:animals}
\end{figure}
 

You will notice that the figure environment is set up as usual. You may also use a table environment for subtables. For each subfloat, you need to use:

\begin{table}[<placement specifier>]
    \begin{subtable}[<placement specifier>]{<width>}
        \centering
        ... table 1 ...
    \caption{<sub caption>}
    \end{subtable}
    ~
    \begin{subtable}[<placement specifier>]{<width>}
        \centering
        ... table 2 ...
        \caption{<sub caption>}
    \end{subtable}
\end{table}

If you intend to cross-reference any of the subfloats, see where the label is inserted; \caption outside the subfigure-environment will provide the global caption.

subcaption will arrange the figures or tables side-by-side providing they can fit, otherwise, it will automatically shift subfloats below. This effect can be added manually, by putting the newline command (\\) before the figure you wish to move to a newline.

Horizontal spaces between figures are controlled by one of several commands, which are placed in between \begin{subfigure} and \end{subfigure}:

  • A non-breaking space (specified by ~ as in the example above) can be used to insert a space in between the subfigs.
  • Math spaces: \qquad, \quad, \;, and \,
  • Generic space: \hspace{''length''}
  • Automatically expanding/contracting space: \hfill

Figures in multiple parts

edit

Sometimes you need to divide up a figure over multiple floats, for instance because the figure is too big to fit on one page. In this case you can use continued figures using the caption package.

Put this in your preamble:

\usepackage{caption}
\DeclareCaptionLabelFormat{cont}{#1~#2\alph{ContinuedFloat}}
\captionsetup[ContinuedFloat]{labelformat=cont}

Then you can use continued floats as follows.

\begin{figure}
	\ContinuedFloat*
	\[ e^{i \pi} + 1 = 0 \]
	\caption{Euler's identity, first form.}
\end{figure}
\begin{figure}
	\ContinuedFloat
	\[ e^{i \pi} = -1 \]
	\caption{Euler's identity, second form.}
\end{figure}
 

Wide figures in two-column documents

edit

If you are writing a document using two columns (i.e. you started your document with something like \documentclass[twocolumn]{article}), you might have noticed that you can't use floating elements that are wider than the width of a column (using a LaTeX notation, wider than 0.5\textwidth), otherwise you will see the image overlapping with text. If you really have to use such wide elements, the only solution is to use the "starred" variants of the floating environments, that are {figure*} and {table*}. Those "starred" versions work like the standard ones, but they will be as wide as the page, so you will get no overlapping.

A bad point of those environments is that they can be placed only at the top of the page or on their own page. If you try to specify their position using modifiers like b or h, they will be ignored. Add \usepackage{dblfloatfix} to the preamble in order to alleviate this problem with regard to placing these floats at the bottom of a page, using the optional specifier [b]. Default is [tbp]. However, h still does not work.

Custom floats

edit

If tables and figures are not adequate for your needs, then you always have the option to create your own! Examples of such instances could be source code examples, or maps. For a program float example, one might therefore wish to create a float named program. The package float is your friend for this task. All commands to set up the new float must be placed in the preamble, and not within the document.

  1. Add \usepackage{float} to the preamble of your document
  2. Declare your new float using: \newfloat{type}{placement}{ext}[outer counter], where:
    • type - the new name you wish to call your float, in this instance, 'program'.
    • placement - t, b, p, or h (as previously described in Placement), where letters enumerate permitted placements.
    • ext - the file name extension of an auxiliary file for the list of figures (or whatever). LaTeX writes the captions to this file.
    • outer counter - the presence of this parameter indicates that the counter associated with this new float should depend on outer counter, for example 'chapter'.
  3. The default name that appears at the start of the caption is the type. If you wish to alter this, use \floatname{type}{floatname}
  4. Changing float style can be issued with \floatstyle{style} (Works on all subsequent \newfloat commands, therefore, must be inserted before \newfloat to be effective).
    • plain - the normal style for LaTeX floats, but the caption is always below the content.
    • plaintop - the normal style for LaTeX floats, but the caption is always above the content.
    • boxed - a box is drawn that surrounds the float, and the caption is printed below.
    • ruled - the caption appears above the float, with rules immediately above and below. Then the float contents, followed by a final horizontal rule.

Float styles can also be customized as the second example below illustrates.

An example document using a new program float type:

\documentclass{article}

\usepackage{float}

\floatstyle{ruled}
\newfloat{program}{thp}{lop}
\floatname{program}{Program}

\begin{document}

\begin{program}
  \begin{verbatim}

class HelloWorldApp {
  public static void main(String[] args) {
    //Display the string
    System.out.println("Hello World!");
  }
}
\end{verbatim}
  \caption{The Hello World! program in Java.}
\end{program}

\end{document}

The verbatim is an environment already discussed in Special paragraphs. It is good for source code, but if you want to introduce a lot of code you might consider using the listings package described in Source Code Listings, that was made just for it.

While this is useful, one should be careful when embedding the float within another float. In particular, the error

not in outer par mode

may occur. One solution might be to use the [H] option (not any other) on the inner float, as this option "pins" the inner float to the outer one.

Newly created floats with \newfloat can also be used in combination with the wrapfig package from above. E.g. the following code creates a floating text box, which floats in the text on the right side of the page and is complete with caption, numbering, an index file with the extension .lob and a customization of the float's visual layout:

\documentclass{article}

% have hyperref package before float in order to get strange errors with .\theHfloatbox
\usepackage{hyperref}

\usepackage{float}

% allows use of "@" in control sequence names
\makeatletter

% this creates a custom and simpler ruled box style
\newcommand\floatc@simplerule[2]{{\@fs@cfont #1 #2}\par}
\newcommand\fs@simplerule{\def\@fs@cfont{\bfseries}\let\@fs@capt\floatc@simplerule
  \def\@fs@pre{\hrule height.8pt depth0pt \kern4pt}%
  \def\@fs@post{\kern4pt\hrule height.8pt depth0pt \kern4pt \relax}%
  \def\@fs@mid{\kern8pt}%
  \let\@fs@iftopcapt\iftrue}

% this code block defines the new and custom floatbox float environment
\floatstyle{simplerule}
\newfloat{floatbox}{thp}{lob}[section]
\floatname{floatbox}{Text Box}

\begin{document}

\begin{floatbox}{r}{}
  \textit{Bootstrapping} is a resampling technique used 
  for robustly estimating statistical quantities, such as 
  the model fit $R^2$. It offers some protection against 
  the sampling bias.
  \caption{Bootstrapping}
\end{floatbox}

\end{document}

Caption styles

edit

To change the appearance of captions, use the caption [7] package. For example, to make all caption labels small and bold:

\usepackage[font=small,labelfont=bf]{caption}

The KOMA script packages [8] have their own caption customizing features with e.g. \captionabove, \captionformat and \setcapwidth. However these definitions have limited effect on newly created float environments with the wrapfig package.

Alternatively, you can redefine the \thefigure command:

\renewcommand{\thefigure}{\arabic{section}.\arabic{figure}}

See this page for more information on counters. Finally, note that the caption2 package has long been deprecated.

Labels in the figures

edit

There is a LaTeX package lpic [9] to put LaTeX on top of included graphics, thus allowing to add TeX annotations to imported graphics. It defines a convenient interface to put TeX over included graphics, and allows for drawing a white background under the typeset material to overshadow the graphics. It is a better alternative for labels inside of graphics; you do not have to change text size when rescaling pictures, and all LaTeX power is available for labels.

A very similar package, with somewhat different syntax, is pinlabel [10]. The link given also points to the packages psfrag and overpic.

A much more complicated package which can be used in the same way is TikZ. TikZ is a front-end to a drawing library called pgf (which is used to make beamer for instance). It can be used to label figures by adding text nodes on top of an image node.

Summary

edit

That concludes all the fundamentals of floats. You will hopefully see how much easier it is to let LaTeX do all the hard work and tweak the page layouts in order to get your figures in the best place. As always, the fact that LaTeX takes care of all caption and reference numbering is a great time saver.

Notes and references

edit

This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.


Previous: Importing Graphics Index Next: Footnotes and Margin Notes