Advanced Documents

Introduction

This Section will cover:

  • Beamer Presentations
  • Writing long documents, such as dissertations or books
  • Tips and Tricks

Beamer Presentation

In the previous parts of the course, you have learned how to create LaTeX documents. Note that until now you have used the article document format as specified by the \documentclass{article} tag. LaTeX includes many other document classes that you can use. As already mentioned at the beginning of the course, the class is essentially several pre-set document parameters, such as the size of pages, default font sizes and families for different environments, as well as specific commands. In this section, you will learn about another very popular class of LaTeX documents called beamer, which allows you to create presentations, like those you could prepare using Microsoft PowerPoint or similar software.

First Beamer Presentation

The first example shows how to create a simple Beamer presentation consisting of two slides. Every beamer presentation begins with \documentclass{beamer}. Beamer slides are called frames and every slide is simply a separate frame environment, opened by \begin{frame} and closed by \end{frame}. As you will see, many familiar structures used in the article class, such as itemize, enumerate or vspace also work in the beamer format.

\documentclass{beamer}

\begin{document}
\begin{frame}
    Sample text on the first slide. \\
    A bullet point list:
    \begin{itemize}
        \item A bullet point.
        \item Another bullet point.
        \item Third bullet point.
     \end{itemize}
     
\end{frame}

\begin{frame}
    Sample text on the second slide. \\
    \vspace{1cm}
    A numbered list:
    \begin{enumerate}
        \item One
        \item Two
        \item Three
    \end{enumerate}
\end{frame}

\end{document}

Title Frame

Most presentations begin with a slide containing its title and author’s credentials. Setting up a title frame in Beamer presentations is like preparing a title page in LaTeX articles. First, you need to specify the title and other details, such as the author’s name, date or institution you work for in the preamble of your document. Then, you simply use the \titlepage tag within the frame environment. Note that in the example it is not necessary to explicitly open and close the frame environment using \begin and \end, as we are using only one tag inside it, and thus we can use a more concise formulation \frame{\titlepage}.

\documentclass{beamer}

\begin{document}
    \begin{frame}
        Sample text on the first slide. \\
        A bullet point list:
        \begin{itemize}
            \item A bullet point.
            \item Another bullet point.
            \item Third bullet point.
        \end{itemize}
\end{frame}

\begin{frame}
        Sample text on the second slide. \\
        \vspace{1cm}
        A numbered list:
        \begin{enumerate}
            \item One
            \item Two
            \item Three
        \end{enumerate}
\end{frame}

\end{document}

Themes

Like other presentation software, LaTeX comes with several pre-defined themes, as well as allows you to define themes of your own. You can select a pre-defined LaTeX theme using \usetheme{} in the preamble of your presentation. Each of the pre-defined themes can also be customized in terms of its colour scheme, using the \usecolortheme{}. Note that you need to provide it with an existing colour scheme name rather than an arbitrary one. You can find an example list of beamer themes and their colour variants here. One of the important properties of the themes is that they often include a footer or a header which appears on every slide, summarising the information about the presentation, such as author, title, date or current slide number. The presentation information you provide in the preamble can often be too long to fit into the footer/header, so you can provide an optional short or abbreviated version of these. To do that, you can use the form \author[short title]{Full title}, where short title will appear in the document footer and full title is only displayed on the title page. This can be seen in the example.

\documentclass{beamer}
\usetheme{madrid}
\usecolortheme{spruce}

\author[Doe]{Jon Doe}
\title[First Beamer]{My First Beamer Presentation}
\subtitle{This is a subtitle}
\institute[PAIS]{University of Warwick \\ Department of Politics and International Studies}
\date[21/02/2020]{21/02/2020 \\ Third LaTeX{} workshop}

\begin{document}

\frame{\titlepage}

\end{document}

Frame Title

Each frame can also have its heading. This is simply added using the \frametitle{title} tag within the frame environment, where title is the heading you want to give to a certain frame.

\documentclass{beamer}
\usetheme{madrid}
\usecolortheme{spruce}

\author[Doe]{Jon Doe}
\title[First Beamer]{My First Beamer Presentation}
\subtitle{This is a subtitle}
\institute[PAIS]{University of Warwick \\ Department of Politics and International Studies}
\date[21/02/2020]{21/02/2020 \\ Third LaTeX{} workshop}

\begin{document}

\frame{\titlepage}

  \begin{frame}
        \frametitle{This is a title for the current slide}
        Some text.
  \end{frame}

  \begin{frame}
        \frametitle{Another title}
        More text.
  \end{frame}

\end{document}

Sections

You can divide a beamer presentation into sections and subsections just as you would do in a LaTeX article. Note that these sections should be defined between frame environments, as shown in the example.

\documentclass{beamer}
\usetheme{madrid}
\usecolortheme{spruce}

\author[Doe]{Jon Doe}
\title[First Beamer]{My First Beamer Presentation}
\subtitle{This is a subtitle}
\institute[PAIS]{University of Warwick \\ Department of Politics and International Studies}
\date[21/02/2020]{21/02/2020 \\ Third LaTeX{} workshop}


\begin{document}

  \frame{\titlepage}

  \section{Introduction}

   \begin{frame}
       \frametitle{This is a title for the current slide}
       Some text.
  \end{frame}

\section{Conclusion}

   \begin{frame}
       \frametitle{Another title}
       More text.
  \end{frame}

\end{document}

AtBeginSection

Note that adding the section did not make any changes to our slide content or titles. This is because, by default, beamer uses section titles only to structure your document (for example, they can be seen when you add a table of contents, which will be discussed later). If you want each section to begin with a section title slide, you need to define that explicitly in the preamble of the LaTeX file, using AtBeginSection{}. You fill the curly braces with a frame, which will appear at the beginning of each section and you can use \insertsectionhead parameter to reference the title of a section. Essentially, you are providing LaTeX with a template of a frame that will be used whenever a new section is started. So, adding this code in the preamble will cause LaTeX to add a slide with vertically centred section title in large bold font at the beginning of each new section. Note that this applies also to subsections – in that case, you would simply use AtBeginSubsection and \insertsubsectionhead.

\AtBeginSection{
    \begin{frame}
        \vfill
        \Huge
        \textbf{\insertsectionhead}
        \vfill
    \end{frame}
}

Colour Boxes

To improve presentation formatting, it is often good to put your text within a box that matches the presentation theme. This can be particularly useful for section title slides discussed before. Such boxes can be added to a beamer slide using the beamercolorbox environment. It is opened by \begin{beamercolorbox}[options]{color}. There are a number of options that can be used in the brackets to customize the box properties. The most useful ones include:

  • sep=dimension - specifies the separation between the text in the box and the box boundaries (dimension is a length value, for example, 5cm or 12pt)
  • center, right and left – specifies the text alignment within the box
  • round = true or false - determines whether the box corners are rounded or not
  • shadow = true or false – specifies whether a shadow appears behind the box
\AtBeginSection{
\begin{frame}
\vfill
\begin{beamercolorbox}[sep=12pt,center,shadow=true,rounded=true]{frametitle}
\Large
\textbf{\insertsectionhead}
\end{beamercolorbox}
\vfill
\end{frame}
}

The curly braces determine to colour of the box. Note that you cannot use colour names or even colour themes as a keyword in the curly braces – instead, you can only refer to colours explicitly defined for the theme you are using or an object within the beamer presentation – it usually makes sense to set it to ‘title’ or ‘frametitle’, which sets the colour of the box to the same one as the background behind the title of the frame.

Table of Contents

Adding a table of contents is as easy as it was in the article class – it is done by simply entering the \tableofcontents tag in a separate frame. So the basic table of contents is set by:

\frame{\tableofcontents}

The \tableofcontents tag also comes with some options. A particularly useful one allows to only highlight the number of the current section in the table of contents. This can be done by using:

\frame{\tableofcontents[currentsection]}

If you start your presentation with a table of contents acting as a presentation outline and want to gradually reveal the titles of subsequent sections while discussing the structure, then the pausesections option might be useful. When it’s used, each new element of the table of contents will be introduced on a new slide. 

\frame{\tableofcontents[pausesections]}

Overlays and Pauses

When delivering a presentation, revealing the entire content of a frame can often be overwhelming for the audience, who may get distracted trying to read everything, instead of listening to the person presenting. To keep everyone focused, it often helps to reveal the information one step at a time. Beamer makes this very easy (arguably easier than other presentation software such as PowerPoint), with the \pause tag. Everything following the tag will appear on the next slide.

\begin{document}
    \begin{frame}
        \frametitle{Title of the slide}
        \pause
        Elements in this slide will appear step-by-step:
        \pause
        \begin{enumerate}
            \item Element One
            \pause
            \item Element Two
            \pause
            \item Element Three
        \end{enumerate}
    \end{frame}
\end{document}

Order of appearance of frame elements can be further customized using overlay specification. The angle brackets (“<” and “>”) used after a markup tag determine on which slides will a certain element or formatting appear. For example, <1> stands for slide number one (of the current frame), <2-4> for the slide range between 2 and 4, and <3,5> for slide 3 and slide 5. The first example shows how it can be applied to a bullet-point list elements appearance:

\frametitle{Title of the slide}
\begin{itemize}
\item<1-4> This appears on all slides. 
\item<2,4> This appears on the second one and the fourth one. 
\item<3> This only appears on the third slide.
\end{itemize}

In the second example, you can see that the overlay specification also works with formattings, such as bold font, italics or font colour. 

\begin{itemize}
\item \textbf<2>{This point will appear in bold on the second slide.}
\item \textit<2>{\color<3>{red}{This point will appear in italics on the second slide and in red on the third.}}
\item \alert<3>{This will be highlighted in in the third slide.}
\end{itemize}

Note that the \alert tag is often used to highlight the text in a colour, which is determined by the presentation theme and colour theme.

Columns

The beamer class also allows you to control the placement of objects within a frame. The columns environment is used to specify a multi-column frame layout, which offers similar functionality to the ‘two content’ and ‘comparison’ layouts in Microsoft PowerPoint. The environment is opened by \begin{columns}[options] and closed by \end{columns}. The options that can be specified are shown in the table below – you can use two of them, by separating them by commas, for example, \begin{columns}[t,onlytextwidth]. To specify a column, simply use \column{width} within the columns environment, where the width parameter controls the width of the column.

\begin{frame}
\begin{columns}[t]
\column{.3\textwidth}
\textbf{Column 1}: \\
\lipsum[1][1-2]
\column{.3\textwidth}
\textbf{Column 2}: \\
\begin{itemize}
\item One
\item Two
\item Three
\end{itemize}
\end{columns}
\end{frame}

Table 1 lists some useful options for the column environment:

Option Description
c Central align columns
b Align column bottoms
t Align column tops
totalWidth = Determines total joint width of the two columns
onlytextwidth Equivalent to totalwidth = ∖∖textwidth
T Also top alignment, however using a different method (if formatting problems occur with t, try using T instead)
Table 1: Column Formatting

Blocks

Blocks are useful when you want to highlight the importance of some text, for example, a quote. They are used to create a separated part of a Beamer frame with its own heading and distinct background color.

\begin{document}
    \begin{frame}
        \begin{block}{\textbf{Important Message}}
            \lipsum[1][1-4]
        \end{block}
        \begin{itemize}
            \item Some
            \item Bullet
            \item Points
        \end{itemize}
    \end{frame}
\end{document}

Figures and Tables

You can use figures and tables in Beamer presentations just as you would in LaTeX articles. For example, you can present the relationship between two variables in two columns, one showing a regression table and the other the scatter plot of the data.

\begin{Verbatim}
\begin{document}
    \begin{frame}
        \begin{columns}[t]
            \column{.3\textwidth}
            \textbf{Column 1}: \\
            \begin{table}[!htbp] \centering 
                \begin{tabular}{lc} 
                    \\[-1.8ex]\hline 
                    & Regressand \\
                    \hline \\[-1.8ex]
                    Regressor & 0.167$^{***}$ \\ 
                    & (0.002) \\ 
                    & \\ 
                    Constant & 0.843$^{***}$ \\ 
                    & (0.073) \\ 
                    & \\ 
                    \hline \\[-1.8ex] 
                    N & 1,000 \\ 
                    R$^{2}$ & 0.823 \\ 
                    \hline \\[-1.8ex]  
                \end{tabular} 
                \caption{Regression results} 
            \end{table} 
            \column{.3\textwidth}
            \textbf{Column 2}: \\
            \begin{figure}[!htbp]
                \includegraphics[width = \columnwidth]{reg_plot.png}
                \caption{Scatter plot}
            \end{figure}
        \end{columns}
    \end{frame}
\end{document}

Summary

The functionalities listed in the previous slides are only a very basic list – Beamer offers many more options and graphic structures than you can use – a comprehensive overview is offered by this rather length Beamer documentation.

Important hint: when working with Beamer in practice, sometimes errors may persist when you re-compile the PDF file (by pressing the “play “ button in TeXStudio) even though your code is correct. In that case, this might be due to the auxiliary files created by TeX when you compile the document –a solution that is always worth trying is deleting these files – either by hand or using the “Clean auxiliary files” option in the “Tools” tab of TeXStudio.

To delete all of them, enter the following list into the “file extensions” field: log,aux,dvi,lof,lot,bit,idx,glo,bbl,bcf,ilg,toc,ind,out,blg,fdb_latexmk,fls,snm,nav,synctex.gz

Books

The last LaTeX document class covered in the course is book. Books can be thought of as a more complex version of the article class – they are likely to consist of multiple chapter files with one “master” file binding them all together. This class is particularly useful when preparing a longer piece of academic work, such as a PhD thesis. This section will briefly go through an example book structure which you can download here. The book folder should always follow a tree-like structure, summarized below. Each chapter is a separate tex file and all the chapters are stored in the same folder. Similarly, all the image files used in the book are stored in a separate folder, with sub-folders corresponding to each chapter number.

 ----\book_template
    |   header.tex
    |   mybook.tex
    |----\bibliography
    |       references.bib
    |----\chapters
    |       01_introduction.tex
    |       02_body.tex
    |       03_conclusion.tex
    |       titlepage.tex
    |----\images
        |---\01
        |       koala.jpg
        |---\02
        |       lemur.jpg
        |---\03
                sloth.jpg

Main File

The main file, mybook.tex binds everything together using the main document environment. The \include command inserts the book chapters in a specified order. The \input command is used to “copy and paste” the content of a tex file. In this case, it inserts the content of the header.tex file, which contains the book’s preamble. Finally, the \addcontentsline command is used to add the “Bibliography” entry to the table of contents.

\input{header}

\begin{document}

    \include{chapters/titlepage}
    \clearpage
    \tableofcontents

    \include{chapters/01_introduction}
    \include{chapters/02_body}
    \include{chapters/03_conclusion}

    %bibliography
    \cleardoublepage
    \addcontentsline{toc}{chapter}{Bibliography}
    \bibliographystyle{apa}
    \bibliography{bibliography/references}


\end{document}

The Preamble File

The header.tex file contains everything that would normally be put in the document’s preamble, i.e. before the \begin{document} statement. Note that this is done for clarity and is not necessary when using a simple book structure like the one in the example – the preamble could simply be placed at the beginning of the mybook.tex file, like in other document classes. However, with the growing complexity of the book, your preamble is likely to get filled with multiple package references and other code customizing the final output. Because of that, storing the preamble in a separate file is likely to make your life easier and keep the length of the main file to a minimum, so that it gives you a good overview of your book’s structure.

When working with large documents, compiling the entire document while working on a specific chapter only may waste a lot of time. To avoid it, you can use the \includeonly tag in the preamble of the book. It explicitly tells the LaTeX compiler which chapter files to use when you hit the “play” button in TeXStudio. For example, using \includeonly{chapters/01_introduction} will mean that the \include tags in the main file referencing other chapters than 01_introduction.tex will be ignored and their content will not be compiled in the final output.

\documentclass[a4paper,12pt]{book}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage{lipsum}

\author{James Doe}
\title{My PhD Thesis}

%this allows you to compile the document with specified chapters only
%\includeonly{chapters/01_introduction}

Chapter File

The chapter file resembles a normal LaTeX document, except for the fact that it has neither a preamble nor a \begin{document} statement. Instead, it just begins with \chapter{chaptertitle}. All the packages used in the chapters are defined globally in the book’s preamble.

\chapter{Introduction}
\section{First section}
Let's begin with citation of \citet{schadkeetal2007}.\\

\lipsum[1-5]
\begin{figure}[!h]
    \centering
    \includegraphics[width = 0.8\textwidth]{images/01/koala.jpg}
    \caption{Picture of a coala}
\end{figure}
\section{Second section}
\lipsum[1-5]

Listings

Reproducibility of results a key prerequisite of methodological transparency and one of the most important facets of quantitative research in social sciences. Every respectable scholar or analyst should allow his audience to go through his research cycle step-by-step, which involves providing them with the original data and the source-code used for the statistical analysis. Reading someone else’s code might often be a difficult task and providing some comments is likely to make it easier. The listings package allows you to include chunks of code in your documents, which makes it possible to prepare technical reports and appendices explaining your quantitative research.

A Basic Example

Like every other package, listings needs to be loaded in the preamble of the document. The first example shows the minimal structure of a document using listings. \lstset{language=R} is used to determine which language will you use as the input (in this case we use R). Then, the lstlisting environment is used to include code in the text. Note, that in the output, a different text style is used for function names, such as function, sqrt, sum, comments and variables to make the code more readable. 

\documentclass{article}
\usepackage{listings}
\lstset{language=R}
\begin{document}
The following function is used to return L2 vector norm:
\begin{lstlisting}
norm <- function(x){
#calculate norm:
sqrt(sum(x^2)) 
}
\end{lstlisting}
\end{document}

Formatting Listings

To make the code you include in your document more readable, you can add additional formatting to the lstlisting environment by setting different parameters through lstset. The example below shows some most important things that can be changed – you can check out the Listings package documentation for an exhaustive list.

\lstset{language=R,
basicstyle=\ttfamily, %style used for listings
numbers=left, %code line numbers
keywordstyle=\color{red}, %set color of keywords to red
commentstyle=\color{blue}\itshape,
stringstyle=\color{magenta}, %set comment color to green
tabsize = 2, %set tabulation style
emph={function}, %emphasize the words you want
emphstyle=\color{red}\underbar, %choose emphasis style
showstringspaces = false, %without this, symbol will replace spaces in strings
deletekeywords = {se,set,data,model},
morekeywords={ggplot,FALSE,TRUE}
}
The following function is used to return L2 vector norm:
\begin{lstlisting}
norm <- function(x){
#calculate norm:
sqrt(sum(x^2)) 
print("Task completed")
}
\end{lstlisting}

See Table 2 for a list of common parameters:

Parameter Description
language Which language you are using. This determines the default keywords to be highlighted.
basicstyle The basic style used for listing. The teletype (\ttfamily) font is a good choice. You can also alter the font size used for the listing.
numbers Location of line numbers
keywordstyle Formatting of language keywords. You can use \color{color} (this requires using color or xcolor packages). Other examples include \itshape for italics, \underbar for underscore and \bfseries for the bold font.
commentstyle Style of the comments.
strinstyle Style of the strings
tabsize Tabulation size
emph, emphstyle This allows you to select a separate style for some words that you want to emphasize in the code
showstringspaces Determines how spaces are shown in strings in the code
morekeywords Allows you to specify additional keywords you want to highlight using the keywordstyle
deletekeywords Allows you to specify keywords you don’t want to be highlighted
Table 2: Formatting of Listings

Using Source Files

Copying and pasting your code might be effortful, especially if you make any changes to it after you put it in your document. Instead, you can use \lstinputlisting[lines]{filename} tag, which allows you to input code directly from the source file you used in the analysis (for example an R script). Additionally, you can use the option brackets [] to specify the lines you want to insert. For example \lstinputlisting[firstline = 2, lastline = 10]{script.R} will input lines 2 to 10 from file script.R (provided that the file is in the same location as the .tex file).

This code was used to produce the table and plot for one of the Beamer slides in the previous part of the course:

\lstinputlisting{graph_table.R}

\bigskip

\textbf{This code generates some toy data:}
\lstinputlisting[firstline = 5, lastline = 7]{graph_table.R}

\bigskip

\textbf{This code runs the regression model and gets the LaTeX output:}
\lstinputlisting[firstline = 10, lastline = 12]{graph_table.R}

\bigskip

\textbf{This code is used for plotting:}
\lstinputlisting[firstline = 14, lastline = 18]{graph_table.R}

Inline code

Finally, you can use your code in the middle of your regular text, by using \lstinline|yourcode|, for example:

I used \lstinline|apply(mydf, 1, function(x) sum(x))| to get a row-wise sum of the \texttt{mydf}.

This makes it easy to reference specific parts of your syntax. It can also be used with a source file, like \lstinputlisting.

Tips & Tricks

This section covers some useful tips, tricks, and extensions of the previously discussed functionalities of LaTeX.

Page Dimensions

The package geometry provides an interface to change global parameters of the document and adjust various page dimensions. This can be done by either loading the package using \usepackage{geometry} and then by using the command \geometry{options} in the preamble of the document, or more concisely by specifying the options when loading the package, by \usepackage[options]{geometry} – these are equivalent and can be used interchangeably, although the majority of LaTeX users seem to prefer the latter since it’s shorter. The options are comma-separated parameters that you may want to adjust, such as the paper size (a4paper, a3paper, legalpaper, etc.), textwidth and textheight (which are self-explanatory) or margin (which sets all the margins to a certain length).

\documentclass{article}
\usepackage{lipsum}
\usepackage[a4paper, margin = 2in]{geometry}
\begin{document}
\lipsum[10-15]
\end{document}
\documentclass{article}
\usepackage{lipsum}
\usepackage{geometry}
\geometry{a4paper, margin = 2in}
\begin{document}
\lipsum[10-15]
\end{document}

These two are equivalent.

The list of some basic parameters is shown in Table 3. Each of them can be set using different LaTeX length units such as cm or in. The total size of the page is divided into the text body and margins, which have separate parameters – this is shown in Figure adopted from the geometry package documentation, which discusses the intricacies of different parameters at length.

Parameter Description
textwidth and textheight Width/height of the body
width and height By default, the same as textwidth and textheight. If includehead = true, includefoot = true or includemp = true, they include header, footer and margin sizes respectively.
top, bottom, left, right Size of specific margins
margin Size of all margins
headheight Height of the header
footsep Spacing between the top of the footnote and the bottom of the text
footskip Distance between the bottom of the text and the bottom of the footnote \
Table 3: Geometry Options

You can also change page dimensions mid-document, using the \newgeometry{options} command in your document with the options listed above. Then, using \restoregeometry will restore the parameters of all pages set after \newpage or \clearpage to those set in the preamble. This is demonstrated in the example.

\documentclass{article}

\usepackage{lipsum}
\usepackage[a4paper, textheight = 28cm, 
textwidth = 20cm]{geometry}


\begin{document}
    \lipsum[10-15]
    \newpage
    \newgeometry{textheight = 20cm, textwidth = 10cm}
    \lipsum[10-15]
    \newpage
    \restoregeometry
    \lipsum[10-15]

\end{document}

Styling

Page number

\pagenumbering{style} – determines the numbering style from the page it’s used on. Note that whenever you use this command, the page numbering starts from the beginning. Styles that can be used include arabic, alph (lowercase letters), Alph (uppercase), roman (lowercase roman numerals), Roman (uppercase roman numerals).

Shortcuts and Special Escapes

Shortcuts

Texstudio also comes with multiple keyboard shortcuts which make preparing documents in LaTeX slightly faster. Some of the most useful shortcuts are listed in Table 4

Shortcut Description
Ctrl/cmd + I Italics, i.e. \textit
Ctrl/cmd + B Bold, i.e. \textbf
Ctrl/cmd + Return Newline \\
Ctrl/cmd + Shift + I New \item in itemize environment
Ctrl/cmd + E New empty environmnent
Table 4: Shortcuts in TeX Studio

Special Escapes

Some of the characters such as “$”, “%”, “#” or “_” have a special meaning in LaTeX and by default are interpreted as elements of the syntax, rather than the text. You can override it by using the “escape” signs, which is the backslash “\”. So, for example, if you want to compile “15%”, you need to typeset “15\%” to escape the percentage character. To escape the backslash itself, use the tag \textbackslash