Adding additional structure to the list of figures/tables

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}
	\addcontentsline{lof}{chapter}{%
		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{lot}{\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}{%
	\addtocontents{lof}{\protect\contentsline{chapter}{%
		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.



Setting PDF meta information

PDFs have meta document information which usually can be read and modified using standard PDF viewers such as Acrobat Reader or Preview (Mac). In Acrobat Reader search for “Properties” in the file-menu. When creating a document using LaTeX, the hyperref package helps setting some of these information, including:

  • Title
  • Author
  • Subject
  • Creator
  • Producer
  • Keywords
  • and many other display and information options (see section 3.6 of the documentation)

 

Here is how:

While loading the package, the meta information is set by specifying key-value pairs in the optional arguments field, i.e.:

\usepackage[key1=value1, key2=value2]{hyperref}

A complete code example:

\documentclass[11pt]{article}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[pdftex,
 pdfauthor=Tom,
 pdftitle={PDF meta information},
 pdfsubject={Sample document with blind text},
 pdfkeywords={hyperref, PDF meta information},
 pdfproducer=TeXShop,
 pdfcreator=pdflatex]{hyperref}
\begin{document}
\blindtext
\end{document}

Using the Acrobat Reader, the meta information can be read and changed through the menu item “file -> properties” (or similar):

pdf meta information

PDF meta information example

A comprehensive list of options is provided in section 3.6 of the hyperref package documentation.


Strict inequalities (greater/less than) in text-mode

Strict inequalities are widely used in math equations as well as within text for comparisons. They can be produced using the ordinary (inline) math-mode ($...$) without loading a specific package.

c > d

$c > d$

d < c

$d < c$

In order to omit the math-mode within a text-paragraph, LaTeX knows text-mode commands for these symbols.

Greater than (>):

\textgreater

Less than (<):

\textless

Non-strict inequalities (\le and \ge), however, can only be produced using the inline math mode.

a \le b

$a \le b$

b \ge a

$b \ge a$

Finally, the equal symbol (=) is available in both text- and math-mode.


bib2tex: Converting bibtex to bibitems

A friend asked me today to help him convert a bibtex-file to a \LaTeX bibliography (\bibitem{}), since the journal he submits his paper to doesn’t accept bibtex-files (*.bib). So what we were trying to do is to convert a set of bibtex-references of the following form (from cell):

@article{bartel2009,
	Author = {Bartel, David P. },
	Date = {2009/01/23},
	Journal = {Cell},
	Month = {01},
	Number = {2},
	Pages = {215--233},
	Title = {Micro{RNA}s: Target Recognition and Regulatory Functions},
	Volume = {136},
	Year = {2009}}

to a format that \LaTeX understands, e.g.:

\bibitem[Bartel(2009)]{bartel2009}
David~P. Bartel.
\newblock Micro{RNA}s: Target recognition and regulatory functions.
\newblock \emph{Cell}, 136\penalty0 (2):\penalty0 215--233, 01 2009.

There is an easy way of converting references by making use of the bibtex-command. It does exactly what we needed in the background. Typesetting the document once (latex) and generating the references with the bibtex-command will create a metafile called “document.bbl”, containing all the referenced bibitems in \LaTeX-format.

tom@texblog:~$ latex document
tom@texblog:~$ bibtex document

Finally, just copy and paste the content of the *.bbl file into the \LaTeX document, overwriting \bibliography{<document>}.

Note: The bibitem above was created using:

\usepackage[numbers, square, comma, sort&compress]{natbib}

Source: fundamentalthinking.


R: Controlling size and placement (subfig) of Sweave-generated figures

I’ve been writing quite a bit of R code recently for my gene expression analysis. Also, I use Sweave (manual) which allows embedding R code “chunks” into TeX documents. When the code is being evaluated, the output (code, calculation results, plots, tables, etc.) will automatically integrated into the document as TeX syntax, making it an extremely handy tool for presentation and documentation purposes.
That said, I will now show how to get a better control of the size and placement of figures generated by Sweave code chunks by manually inserting them into a TeX document.

Let me first give a general Sweave example with a single plot and later extend it with a second, placing them side-by-side. The following code chunk defines a vector x and a function f.

<<echo=F, results=hide>>=
x <- seq(-2, 2, by=0.1)
f <- function(x) { x^3 }
@

Now we use Sweave to plot the function f and integrate the result into the TeX document:

\begin{figure}
\begin{center}
<<fig=TRUE, echo=FALSE>>=
plot(x, f(x), cex=0.3)
@
\caption{Function plot of $x^3$ between $-2$ and $2$.}
\end{center}
\end{figure}

And here is the result:
Sweave1

Imagine now that we want to place plots of two functions, f(x)=x^2 and f(x)=x^3, side-by-side using the subfig package. This cannot be done automatically, since there is no way to control the figure size in the final pdf directly from within the Sweave chunk. Therefore, we generate the figures and add them manually, giving us complete control of size, angle and trimming of the figure (see graphicx).

Here is the complete code:

\documentclass[11pt]{article}
\usepackage{graphicx, subfig}
\begin{document}

<<echo=FALSE, results=hide>>=
x <- seq(-2, 2, by=0.1)
f2 <- function(x) { x^2 }
f3 <- function(x) { x^3 }
@

\begin{figure}[ht]
\begin{center}
\subfloat[Function plot of $x^2$ between $-2$ and $2$.]{

<<label=xsquare, fig=TRUE, echo=FALSE, include=FALSE>>=
plot(x, f2(x), cex=0.3)
@

\includegraphics[width=0.4\textwidth]{sweave-xsquare}
}
\qquad
\subfloat[Function plot of $x^3$ between $-2$ and $2$.]{

<<label=xcube, fig=TRUE, echo=FALSE, include=FALSE>>=
plot(x, f3(x), cex=0.3)
@

\includegraphics[width=0.4\textwidth]{sweave-xcube}}
\end{center}
\end{figure}
\end{document}

Basically, the code generates the plots (pdfs). We don’t want them to be automatically included into the document, which is achieved through the include=FALSE option. Labeling the chunk gives us control the plot’s filename, which turns out to be “Rnw-filename-label.pdf” (Rnw is a Sweave file extension). In case you prefer the figures not to have the filename of your source-file, there is a Sweave option that globally controls the figure-filename-prefix and the directory to which they are saved:

\SweaveOpts{prefix.string=<directory>/<filename-prefix>}

Finally, we manually add our plots using the standard LaTeX \includegraphics-command and the subfig-package (see this post for more details). In case you prefer png and/or eps figures, use the pdf, png, eps options:

<<label=xcube, fig=TRUE, echo=FALSE, pdf=FALSE, eps=TRUE, png=TRUE, include=FALSE>>=

Sweave2


Reverse enumerate or etaremune

I stumbled across this package recently thanks to a comment by ofer.

Basically, the etaremune package inverses the enumerate counter, making the indices decreasing rather than increasing.

Basic example:

\documentclass{article}
\usepackage{etaremune}
\begin{document}
\begin{etaremune}
	\item Third item
	\item Second item
	\item First item
\end{etaremune}
\end{document}

basic_etaremune

Basic etaremune example.

Furthermore, to make the package more flexible, it offers different customizations.

Starting number:

The start option, lets you begin with an arbitrary number. In case the starting number is smaller than the number of items, the counter won’t further decrease once it reaches zero.

\usepackage{etaremune}[start=7]

Nesting (with enumerate):

Normal lists can be nested and so can etaremune lists. The lists can also be mixed with normal, enumerate lists. The documentation has a very nice example which I will just reuse here:

\renewcommand{\labelenumi}{\theenumi)}
\renewcommand{\theenumii}{\roman{enumii}}
\begin{enumerate}
	\item First.
	\begin{etaremune}
		\item third.\label{notice}
		\item second.
		\item first.
	\end{etaremune}
	\item Second.
	\item Third.
\end{enumerate}
Notice item~\ref{notice}.

Controlling the style:

Finally, the package allows the usage of some options for both, global and local style control.

Global options:

\usepackage[<options>]{etaremune}

Local options:
\begin{etaremune}[<options>]

Available options:

Vertical lengths control:
\topsep, \partopsep, \itemsep and \parsep.

Horizontal lengths control:
\leftmargin, \rightmargin, \listparindent, \itemindent, \labelwidth and \labelsep.

Here is the example from above slightly extended with the options itemsep and parsep set to zero. The first reduces the space between items of the same level to a minimum, whereas the latter between levels.

\documentclass{article}
\usepackage{etaremune}
\begin{document}
\renewcommand{\labelenumi}{\theenumi)}
\renewcommand{\theenumii}{\roman{enumii}}
\renewcommand{\theenumiii}{\Alph{enumiii}}
\begin{enumerate}
	\item First
	\item Second
	\begin{etaremune}[itemsep=0pt,parsep=0pt]
		\item third.\label{notice}
		\item second.
		\begin{etaremune}
			\item subsecond
			\item subfirst
		\end{etaremune}
		\item first.
	\end{etaremune}
	\item Third
\end{enumerate}
Notice item~\ref{notice}.
\end{document}

etaremune example

etaremune example


Including pages from PDF documents

The package pdfpages let’s you include a complete PDF or any combination of pages into a LaTeX document.

First load the package in the preamble.

\usepackage{pdfpages}

Now use any of the possible options below to include pages from a PDF.

Include the first page

\includepdf{file}

The whole document

\includepdf[pages=-]{file}

A forward or backward range

\includepdf[pages=2-8]{file}
\includepdf[pages=8-2]{file}
\includepdf[pages=last-1]{file}

You never know when that may come in handy. However, the keyword last actually can be quite useful in case the number of pages in the document may change.

Several single pages with/without blanks

\includepdf[pages={3, 6, 1}]{file}
\includepdf[pages={3, {}, 9}]{file}

Copies of the same page

\includepdf[pages={5, 5, 5}]{file}

And finally, a bit of everything

\includepdf[pages={3-6, {}, 1, 7}]{file}

The package also provides the option nup=axb to print several logical pages on a single physical page (the parameter a being the number of columns and b the number of rows). LaTeX scales the logical pages to fit within the margin of the physical page. In the example below the first 4 logical pages will be placed on the first physical page and the rest on the next.

\includepdf[nup=2x2, pages=1-7]{file}

Pdfpages package documentation.


Increase enumerate & itemize depth with enumitem

The default maximum depth for the list environments enumerate and itemize is four. Using more than four nested levels will lead to the error: “Too deeply nested”.

One way to increase the depth of a list is using a mix of enumerate and itemize. However, obviously, some levels will be a bulleted rather than enumerated.

The enumitem package allows you to define new lists with an arbitrary number of levels. For example, let’s create nested lists with up to five levels.
Define a new list longenum of type enumerate which has 5 levels. Set the label style for each level they way you like. I used roman, alph and arabic.

\usepackage{enumitem}
\newlist{longenum}{enumerate}{5}
\setlist[longenum,1]{label=\roman*)}
\setlist[longenum,2]{label=\alph*)}
\setlist[longenum,3]{label=\arabic*)}
\setlist[longenum,4]{label=(\roman*)}
\setlist[longenum,5]{label=(\alph*)}

That’s all you need to know. The rest is straight forward, just use longenum instead of enumerate for each level and create a nested lists with up to 5 levels.

Here is the complete sample code with the output below:

\documentclass[11pt]{article}
\usepackage{enumitem}
\newlist{longenum}{enumerate}{5}
\setlist[longenum,1]{label=\roman*)}
\setlist[longenum,2]{label=\alph*)}
\setlist[longenum,3]{label=\arabic*)}
\setlist[longenum,4]{label=(\roman*)}
\setlist[longenum,5]{label=(\alph*)}
\begin{document}
\section*{Enumerated list with 5 levels}
\begin{longenum}
	\item Level 1 first
	\item Level 1 second
	\begin{longenum}
		\item Level 2 first
		\item Level 2 second
		\begin{longenum}
			\item Level 3 first
			\item Level 3 second
			\begin{longenum}
				\item Level 4 first
				\item Level 4 second
				\begin{longenum}
					\item Level 5 first
					\item Level 5 second
				\end{longenum}
			\end{longenum}
		\end{longenum}
	\end{longenum}
\end{longenum}
\end{document}

Enumitem package documentation.


Quick note on line spacing

There are two different ways to change line spacing in LaTeX. One is simpler, the other requires a package, but is more flexible.

Let’s start easy.

The linespread-command:

To change the line spacing for the entire document, you can use the linespread command in your preamble:

\linespread{<factor>}

The factor is somewhat confusing. For double-spacing you have to use 1.6 and for one-and-a-half spacing 1.3. Not very intuitive, but I'm sure there is a reason for it.

The setspace-package:

Personally, I prefer the setspace package, which is more straight forward in usage, provides more flexibility and is easy to use as well:

\usepackage{setspace}
\singlespacing
\onehalfspacing
\doublespacing
\setstretch{<factor>} % for custom spacing

You can change spacing back and forth within your document using the commands above.
However, in order to stay on top of things, it's usually better using an environment to change vertical spacing locally.

\begin{doublespace}
...
\end{doublespace}

or

\begin{spacing}{2.0}
...
\end{spacing}

Finally, the package provides improved vertical spacing on top and below of itemize and quote environments, for any other than single-space content:

\usepackage{setspace}
\doublespacing
...
\begin{singlespace*}
\begin{quote}
Quote
\end{quote}
\end{singlespace*}

And that's the difference:

Single space quote with default vertical spacing

Default vertical spacing

Single space quote with improved vertical spacing

Improved vertical spacing

The package is documented within the style-file


10 ways to customize toc/lof/lot

I put together this list of 10 ways to customize the Table of Contents, List of Figures and List of Tables. Some of them are pretty common, some may be new to you. Hope you enjoy the list…

Some pieces of code below require the tocloft package which provides extensive customization functionality for table of contents, list of figures and list of tables. It will be indicated wherever the tocloft or any other package needs to be loaded in the preamble.

Note: I will use the abbreviations toc for table-of-contents, lof for list-of-figures and lot for list-of-tables in the article below.

1. Change the lists headings

Change the heading can be done without loading any specific package. Obviously, the name has to be changed before creating the list.

\renewcommand\contentsname{}
\tableofcontents
\renewcommand\listfigurename{}
\listoffigures
\renewcommand\listtablename{}
\listoftables

2. Add “Page” above page numbers

Several people asked me how to place the word “Page” on top of the page numbers in toc/lof/lot. Here is how you do it:

\tableofcontents
\addtocontents{toc}{~\hfill\textbf{Page}\par}
\chapter{...}

"Page" above page numbers

It works the same way with lof and lot. The code was taken from here.

3. Change depth of entries

You can change the depth, i.e. how many levels shall be printed using the respective counter:

\setcounter{tocdepth}{1}
\tableofcontents

0: chapter (not available for \documentclass{article),
1: section,
2: subsection, etc.
The default depth is 3, subsubsection.
Similarly, including subfigures and subtables can be achieved using:

\setcounter{lofdepth}{2}
\setcounter{lotdepth}{2}

4. Roman page numbers for toc/lof/lot

To get a different page number style for toc/lof/lot, use:

\pagenumbering{}

and change it back to arabic before the first chapter starts.

Available styles are arabic, roman, Roman, alph and Alph.

Complete code example:

...
\pagenumbering{roman}
\tableofcontents
\listoffigures
\listoftables
\clearpage
\pagenumbering{arabic}
\chapter{...}
...

5. Hyperlinks to content

Loading the hyperref package will let you navigate from toc/lof/lot entries directly to the respective content:

\usepackage{hyperref}

If you only want the page number to be clickable, you’ll need to load the package with the following option:

\usepackage[linktocpage=true]{hyperref}

6. Adding the lists to toc

Adding entries to toc/lof/lot can be done manually with a single command. Usually, to be sure the page number is correct, it’s advisable to add entries directly before or after the actual content to list. And here is how:

\addcontentsline{}{}{}

The file line(s) shall be added (toc, lof or lot), the type of the entry (chapter, figure, etc.) and the entry text itself.

To add the three lists to the toc use:

\tableofcontents
\addcontentsline{toc}{chapter}{Contents}
\listoffigures
\addcontentsline{toc}{chapter}{List of Figures}
\listoftables
\addcontentsline{toc}{chapter}{List of Tables}

Adding toc/lof/lot to contents

7. Changing the font of entries

To change the way the actual entries look, you can make use of a command provided by the tocloft package. The command will affect the number as well as the text. However, it will not change the page number and the separator (if there are any). The nice thing here is that since it’s placed just in front of the sequence number, you can also use it to add words such as “Chapter 1: Biology … Here are a few examples for illustration:

\usepackage{tocloft}
\renewcommand{\cftchapfont}{\scshape}
\renewcommand{\cftsecfont}{\bfseries}
\renewcommand{\cftfigfont}{Figure }
\renewcommand{\cfttabfont}{Table }

Try it and make sure you don’t forget the space behind Figure_ and Table_, otherwise it will be glued to the number.

8. Creating you own list of …

Again, the tocloft package has to be loaded. First, define a new list environment as well as the item which are later being listed. In this case, we are defining lemmas, but it could also be proofs, equations, a special list of figures, footnotes, anything. The last line of the lemma command defines how lemmas should be numbered, here “chapter.lemma”.

\usepackage{tocloft}
...
\newcommand{\listoflemmas}{List of Lemmas}
\newlistof{lemma}{lem}{\listoflemmas}
\newcommand{\lemma}[1]{%
  \refstepcounter{lemma}
  \par\noindent\textbf{Lemma \thelemma. #1}
  \addcontentsline{lem}{lemma}
  {\protect\numberline{\thechapter.\thelemma}#1}\par
}
...
\listoflemmas
...
\lemma{My first lemma}
\label{lem:lemma1}

You can find a complete code example here.

9. Alternative text in toc/lof/lot for headings and captions

In case your caption is too long for the lof/lot, you can give it an alternative text. Similarly, the headings can be given an alternative name in the toc:

\caption[]{}
\chapter[]{}

10. Chapter specific tocs with minitoc

Finally, minitoc produces beautiful tocs at the beginning of every chapter (or any other heading) and therefore, I will dedicate this 10th and last entry to that package:

\usepackage{minitoc}
...
\dominitoc
\tableofcontents
...
\chapter{...}
\minitoc

A minitoc example

Here is an earlier post I wrote about the package as well as the complete documentation.

Wow, that’s the longest post I ever wrote. Hope you’ve enjoyed my list, have fun customizing :-) .


Follow

Get every new post delivered to your Inbox.

Join 177 other followers