Advanced LATEX

Tim Love

August 5, 1999

  • LATEX Concepts

    • Environments and commands
    • Classes and packages
    • Errors
    • Files created
    • How to use LATEX at CUED
  • Document structure
    • Counters and Length parameters
    • Document and page organisation
    • Pagebreaks, space, footnotes, references, boxes, etc
  • Color and Fonts
    • Colored text
    • Special characters
    • Font Sizes
    • Font Types
    • Postscript Fonts
    • Font attributes
    • Selection commands
  • Environments
    • Alignments
    • Listing Items
    • Tabular
    • Array
    • Pictures
    • Maths
    • Figures
    • Tabbing
    • Verbatim
    • Quote, abstract
    • Letter
    • Curriculum Vitae
  • Customising
    • Macros
    • Modifications
    • New Commands
    • Packages
    • An Example


LATEX Concepts

  • Environments and commands

  • Classes and packages
  • Errors
  • Files created
  • How to use LATEX at CUED


Environments and commands

LATEX is a macro-package for TEX which has many preset environments where much of the setting up that TEX users have to do explicitly is done for you. An environment has the form

\begin{environment name}

.

\end{environment name}

LATEX also has commands which affect the formatting of the document. Their arguments are given in braces. For example,

  \textit{This is much more important} than this.

produces as output This is much more important than this.

The related \itshape command doesn't take an argument. It affects all the subsequent text in the environment where it's used.

LATEX tries to enforce the idea that the visual appearance of the document (use of fonts, indentation, etc) should derive from the logical structure of the document (i.e. rather than manually putting the section titles into bold, you should let the \section command do it). Resisting this philosophy can lead to extra (usually unnecessary) work.

LATEX is expandable. Many macros can be loaded in to provide added featues. You can also create your own commands and environments. Commands can take arguments that modify their action

  • Some commands have a *-form, a variant on the standard command that you get by adding a * to the command name.

  • Mandatory arguments are enclosed in {} braces

  • Optional arguments are enclosed in [ ] brackets.


Classes and packages

At the top of your file you will have a line something like

\documentclass[12pt]{article}

which determines the font size and document class - the type of document you're writing. Each class has an associated *.cls file in the system directories which is read in at start-up time. Other options accepted by article include 10pt, 11pt and twocolumn.

Then you'll probably need to load in extra macros with the \usepackage command. Each package has an associated *.sty file in the system directories. The packages inherit the options from the \documentclass line and can be given others of their own. E.g.

\usepackage[dvips]{graphicx}
\usepackage[dvips]{color}

tells LATEX that you want to use the extra graphicx and color macros, and that you are going to use dvips to convert the resulting file to postscript. You can shorten this to

\usepackage[dvips]{graphicx,color}


Errors

Errors can be reported either from the LATEX phase (in which case it is reported as such) or the lower level TEX phase. Don't be too put off by the half-digested text displayed. A line number is reported which usually helps to detect the error. Typing `h' sometimes produces helpful diagnostics. The most common errors reported are

  • a command misspelt

  • a mismatched brace

  • improper use of special characters

  • forgetting to have the appropriate \usepackage{...} lines.

  • a error like this

    Overfull \hbox (15.42563pt too wide) in paragraph at lines
    285--288 \OT1/ppl/m/n/10 You can cre-ate ver-tical space
    between lines or ho-ri-zontal space   between

    means that lines 285 to 288 are producing a text line about 15 pts (about 5mm) too wide. \OT1/ppl/m/n/10 is the specification of the font used. When TEX does right and left alignment, it works out how much space it needs to leave between words and where to hypenate words if necessary. But the amount of space it's prepared to leave has to fall within a certain range and it will only split words in certain places (shown in the error message by a hyphen). If these restrictions mean that LATEX can't produce a satisfactory line, it will produce as much of the line as it can. A re-phrasing of the offending sentence will usually solve the problem. Another thing you might try is to control the way a troublesome word is hyphenated using something like

    \hypenation{furthermore fur-ther-more}

    at the top of your file. If all else fails, use {\sloppy...} to enclose the offending text.

  • LATEX issues a *.

    This means LATEX needs more input. It probably means you've missed out an \end{document}, but if not you may be able to get LATEX to continue processing as best it can by typing <Return>.

  • ! Argument of \label has an extra }

    If you're sure you haven't left out a left brace, then maybe you need to protect the inmost (fragile) command. For example, in some older versions of LATEX \label is fragile which causes a problem in \caption{Picture\label{margin}}, so the safer construction \caption{Picture\protect\label{margin}} has to be used.


Files created

More than just the .dvi file may be produced. Don't worry about them - except perhaps for the log file you won't need to look at them.

  • .aux - cross references, etc

  • .toc - created by \tableofcontents
  • .lof - created by \listoffigures
  • .lot - created by \listoftables
  • .log - a copy of the diagnostic output that usually comes out on the screen.

Some common errors can be found using the lacheck program on the LATEX file.


How to use LATEX at CUED

From the command line -

After running latex at least twice, you should be able to preview your *.dvi document using xdvi and print it using plotview, but if postscript is implicated at all (if you load in graphics, use postscript fonts, scale, use color, or rotate) then you should convert your *.dvi document to postscript. A typical sequence of commands to process doc.tex would be

 latex doc
 latex doc
 dvips doc.dvi -o doc.ps
 ghostview doc.ps
 lp -dljmr1 -opostscript doc.ps

Using xlatex -

xlatex has buttons to process, preview and print your document (or selected pages of it), and convert it to postscript. Just type xlatex filename.

Writing a LATEX document is rather like writing a program. This makes using LATEX more difficult in some respects than using a word processor, but there are advantages too. For instance creating a table of contents is trivial. Beginners often use unnecessary `\\' sequences and write `{\large \textbf{2.1 Method}}\\' when `\subsection{Method}' would be much better. Users who think they know more about typesetting than LATEX (those who, for example, like underlining) will waste a lot of time too.

Avoid repeating constructions. Instead, write your own macros and commands, and familiarise yourself with the packages.


Document structure

  • Counters and Length parameters

  • Document and page organisation
  • Pagebreaks, space, footnotes, references, boxes, etc


Counters and Length parameters

  • Counters :- LATEX maintains many counter variables (e.g. page, part, equation, footnote, chapter, paragraph, section, subsection, subsubsection, enumi, etc). You can set these counters yourself. Some examples:-

    \setcounter{page}{0}
    \addtocounter{chapter}{2}

  • Length Parameters :- LATEX accepts the following units of length: in, cm, mm, pt (there are 72.27 pts to an inch), em (width of an M), ex (height of an x). These units can be used to set the values of length variables using \setlength. For example,

    \setlength{\parindent}{0in}

    sets to zero the amount by which the first line of a paragraph is indented. Other useful length parameters are:-

    parskip:-

    determines the gap between paragraphs.

    baselineskip:-

    determines the usual distance from the bottom of one line to the bottom of the next. You can adjust this to produce double spacing, but a better way, which takes a stretch factor as argument is to use \linespread. For instance before \begin{document} you can do

    \linespread{1.6}

    to get doublespacing through your document. The setspace package offers more options.


Document and page organisation

  • Document classes: The standard classes are article, book, letter, report, slides. The differences between these are often minor. A book can have chapters. In a report sections begin at 0 whereas in an article they begin at 1. Just about all our handouts are articles.

  • Big Documents :- It's best to split your document into smaller files and have a master file looking like this

     \documentclass[dvips,12pt]{book}
     \usepackage{a4,color,graphics,palatino,fancyhdr}
     \begin{document}
     \pagestyle{empty}
     \tableofcontents
     \listoffigures
     \pagestyle{fancy}
     \input{chapter1}
     \input{chapter2}
     \input{fig2}
     \input{chapter3}
     \input{chapter4}
     \appendix
     \input{appendices}
     \end{document}

    on which you can run latex just as if the master file contained all the text of chapter1.tex etc. The advantage of this is that once you have a chapter correct, you can comment out the corresponding `input' line and avoid unnecessary processing. Remember to take out the \begin{document} and \end{document} lines from the component files.

  • Page Size :- You can choose the margin sizes yourself by changing the following dimensions before the \begin{document} line.

    \setlength{\topmargin}{-0.4in}
    \setlength{\topskip}{0.3in}    % between header and text
    \setlength{\textheight}{9.5in} % height of main text
    \setlength{\textwidth}{6in}    % width of text
    \setlength{\oddsidemargin}{0.75in} % odd page left margin
    \setlength{\evensidemargin}{0.75in} % even page left margin

    Note that a margin width of 0cm gives you a margin 4cm wide. Rather than set absolute sizes you can modify the default sizes using commands like the following -

    \addtolength{\evensidemargin}{-1cm}
    \addtolength{\oddsidemargin}{-1cm}
    \addtolength{\textwidth}{2cm}

    Further support for control of page layout is provided by the geometry package. To see the current values of these dimensions, use the layout package, which defines a \layout command.

    For A3 output, add \usepackage{a3} to your latex source file (foo.tex say), run latex on it, convert the resulting file to Postscript using ``dvips -t a3 foo.dvi -ofoo.ps'' then print using ``lp -oa3 -dljmr2 foo.ps''.

  • Title Pages :- The title page of this document was created by the following LATEX commands.

    \title{Advanced \LaTeX}
    \author{Tim Love}
    \date{\today}
    \maketitle

  • Contents :- Use \tableofcontents to create a contents list at that point in the document. LATEX will pick out the sections, subsections etc for you. You'll have to run LATEX at least twice though.

  • Page numbers and Headings :- These are determined by the argument given in pagestyle{}.

    plain :-

    the page numbers are put at the bottom of the page. The top of the page is empty. This is the default mode.

    empty :-

    this suppresses page numbering altogether, except on the title page it you're using \maketitle. The workaround in this case is to do

    \maketitle
    \thispagestyle{empty}

    with no gap between the two lines.

    headings :-

    this puts the page numbers at the top and adds a header whose contents depend on the document style.

fancyhdr is a popular package that adds useful page headers when the command \pagestyle{fancy} is used. This handout uses it.

Long section titles can cause trouble in headers. The section commands let you specify an extra, shorter title for use in the header and contents page. Section 2.3 was specified as follows

    \subsection[Pagebreaks, footnotes, etc]
       {Pagebreaks, space, footnotes, references, boxes, etc}

  • Sectioning :- To start a chapter called Life in a book, just use \chapter{Life}. Similar commands to start a part, section or subsection also exist in most document classes (articles don't have chapters or parts though).

    If you use the *-form of the command then the sections will not be numbered, neither will it appear in the table of contents.

    A title will only be numbered if its 'depth' isn't more than secnumdepth and will only appear in the contents page if the 'depth' isn't more than the value of tocdepth. So, for example, doing

    \setcounter{tocdepth}{2}
    \setcounter{secnumdepth}{3}

    will cause section 1.4.3 to be numbered, but it won't appear in the contents.


Pagebreaks, space, footnotes, references, boxes, etc

  • Page Breaks :- you can force a page break using \newpage.

  • Preventing line breaks :- If there's a word that you don't want broken, put it in an mbox. E.g.,

    One shouldn't try to break up \mbox\emph{relationships}

  • Space :-

    You can create vertical space \vspace{.5cm} between lines
    or horizontal space \hspace{1.5cm} between words.
    The arguments to these commands can be negative.

    You can create vertical space

    between lines or horizontal space between words. The arguments to these commands can be negative. \vspace* will create space even at the top of a page. It's sometimes useful to create stretchable space. The following creates space that pushes the letters to the edge of the page

    \noindent A\hspace{\stretch{1}} B\\
    C\hspace{\stretch{1}} D

    A B
    C D

  • Footnotes :-

    Do them like this\footnote{I told you so.}

    Do them like this1 The footnotes are numbered by default. If you want to use symbols (stars, daggers etc) then you need to redefine how the footnote counter is displayed.

    \def\thefootnote{\fnsymbol{footnote}}

  • Margin notes :-

    Do them like this\marginpar{margin note}

    Do them like this

  • Cross References :- At the end of this source file is the line \label{THE_END}. \pageref{THE_END} will refer to the final page by number, and \ref{THE_END} will refer to it by section number. The last page is in section 6. You'll have to run LATEX at least twice to pick up forward references like these.

  • Boxed Text :- For short pieces of text, use \fbox

       Help. I'm \fbox{trapped}

    Help. I'm

  • Comments :- Anything to the right of a % character is ignored by LATEX .

  • Rules :- The \rule takes 2 arguments; a width and a height, so

    \rule{\textwidth}{1pt} produces


Color and Fonts

  • Colored text

  • Special characters
  • Font Sizes
  • Font Types
  • Postscript Fonts
  • Font attributes
  • Selection commands


Colored text

Commands that control foreground and background colors need

   \usepackage[dvips]{color}

after the \documentclass line but before \begin{document}.

  • \textcolor{colorname}{text} writes text in a color which can be specified by name (black, white, red, green, blue or a color name you've defined), RGB components, or grayscale.

  • \colorbox{colorname}{text} writes text in a box with a colored background.
  • \fcolorbox{framecolor}{boxcolor}{text} writes text in a colored frame.
  • \pagecolor{colorname} sets the color of the page's background.
  • \definecolor{colorname}{color specification} lets you define new color names.

\definecolor{gold}{rgb}{0.85,.66,0}
This is in \textcolor{red}{red} and this box is \colorbox{gold}{gold}.
Text color can be set using RGB values
(\textcolor[rgb]{0,1,0}{like so}), or \textcolor[gray]{0.2}{shades}
\textcolor[gray]{0.5}{of} \textcolor[gray]{0.8}{grey}.

produces

This is in red and this box is gold. Text color can be set using RGB values (like so), or shades of grey.


Special characters

is created by \dag, [image] by \ddag, § by \S, ¶ by \P, £ by \pounds, ö by \"{o}, © by \copyright. Many others are available in the math environment, including all the lower case greek letters and most of the upper case ones. If you only want to use a few characters you can bracket the symbols using $ and $ rather than \begin{math} and \end{math}. You can put a slash through any of these characters by prefacing them with \not

\sqrt{i} | \sqrt[5]{x+iy} | \ldots
\cdots | \vdots | \ddots
\alpha | \beta | \gamma
\delta | \omega | \Gamma
\Theta | \Omega | \pm
\mp | \div
\ast | \star | \circ
\bullet | \cdot | \cap
\bigcap | \cup | \bigcup
\uplus | \biguplus | \sqcap
\sqcup | \bigsqcup | \vee
\bigvee | \wedge | \bigwedge
\setminus | \wr | \diamond
\bigtriangleup | \bigtriangledown | \triangleleft
\triangleright | \oplus |
\bigoplus | \ominus | \oslash | \odot
\bigodot | \bigcirc | \amalg
\leq | \prec | \preceq
\ll | \subset | \subseteq
\in | \vdash |
\geq | \succ | \succeq
\gg | \supset | \supseteq
\sqsupseteq | \ni | \dashv
\equiv | \asymp | \approx | \cong
\neq | \doteq | \propto
\models | \perp | \mid
\parallel | \bowtie | \smile
\frown | \leftarrow | \Leftarrow
\rightarrow | \Rightarrow | \leftrightarrow
\Leftrightarrow | \mapsto | \hookleftarrow
\leftharpoonup | \leftharpoondown | \rightleftharpoons
\longleftarrow | \Longleftarrow | \longrightarrow
\Longrightarrow | \longleftrightarrow | \Longleftrightarrow
\longmapsto | \hookrightarrow | \rightharpoonup
\rightharpoondown | \uparrow | \Uparrow
\downarrow | \Downarrow | \updownarrow
\nearrow | \searrow | \swarrow
\nwarrow | \aleph | \hbar
\jmath | \ell
\wp | \Re | \Im
\empty | \nabla
\surd | \top | \bot
\| | \angle | \forall
\exists | \neg | \flat
\natural | \sharp | \backslash
\partial | \infty | \triangle
\clubsuit | \diamondsuit | \heartsuit
\spadesuit | \sum | \prod
\coprod | \int | \oint


Font Sizes

These are the available sizes.

tiny | scriptsize | footnotesize | small | normalsize
large | Large | LARGE | huge | Huge

If, for example, you want to use the smallest size, do

{\tiny ... }

If Huge isn't big enough for you, you can scale a postscript font up using the commands designed for graphics. \resizebox{!}{5cm}{BIG} produces


Font Types

Independent of size, these font types are at your disposal :- \textrm (roman), textit(italic), \textsc (SMALL CAPS), \emph (emphasis, but note that if you use emph within emphasized text, you will get roman text), \textsl (slanting), \texttt (teletype), \textbf (boldface), \textsf (sans serif). As long as there's no conflict, these commands can be combined so that, for instance, this is bold sans serif can be produced by \textsf{\textbf{this is bold sans serif}}.


Postscript Fonts

It is easy to write a document that has postscript fonts. We have package support for helvetica (helvetic), utopia, times, optima, newcentury (newcentu), palatino and courier. To use palatino, for instance, all you need to do is add

\usepackage{palatino}

to your file. The pifont package has special commands for using the Zapf Dingbats font. \dingfill{40} completes the line with the specified symbol 40

and \dingline{36} draws a whole line of symbols. 36

It's a good idea to use a font that's installed in the printer you intend to use. See the table on page [*] for information about the teaching system's ljmr1 printer.


Font attributes

The commands above should give you sufficient control over fonts. If you don't want to know more at the moment then turn to section 4

Every text font in LATEX has five attributes:

encoding

This specifies the order that characters appear in the font. The most common values for the font encoding is OT1.

family

The name for a collection of fonts, usually grouped under a common name by the font foundry. For example, `Adobe Times' and Knuth's `Computer Modern Roman' are font families. There are far too many font families to list them all, but some common ones are:

Internal fontname

Fontname

In ljmr1?

cmr

Computer Modern Roman

No

cmss

Computer Modern Sans

No

cmtt

Computer Modern Typewriter

No

cmm

Computer Modern Math Italic

No

cmsy

Computer Modern Math Symbols

No

cmex

Computer Modern Math Extensions

No

ptm

Adobe Times

Yes

phv

Adobe Helvetica

Yes

pcr

Adobe Courier

Yes

pun

Univers

No

ppl

Palatino

Yes

pagk

AvantGarde-Book

Yes

pagd

AvantGarde-Demi

Yes

pbk

Bookman

Yes

put

Utopia

No

pop

Optima

No

pnc

New Century Schoolbook

Yes

pzd

ZapfDingbats

Yes

rpad

Garamond

No

series

How heavy or expanded a font is. For example, `medium weight', `narrow' and `bold extended' are all series. The most common values for the font series are:

m

Medium

b

Bold

bx

Bold extended

sb

Semi-bold

c

Condensed

shape

The form of the letters within a font family. For example, `italic', `oblique' and `upright' are all font shapes. The most common values for the font shape are:

n

Normal (that is `upright' or `roman')

it

Italic

sl

Slanted (or `oblique')

sc

Caps and small caps

size

The design size of the font, for example `10pt'.

These five parameters specify every LATEX font, for example:

 |  |  |  |  | Font
OT1 | cmr | m | n | 10pt | Computer Modern Roman 10pt
OT1 | cmss | m | sl | 12pt | Computer Modern Sans Oblique 12pt
OML | cmm | m | it | 10pt | Computer Modern Math Italic 10pt
T1 | ptm | b | it | 18pt | Adobe Times Bold Italic 18pt


Selection commands

There are commands to set attributes one at a time:

Command | Attribute | Value in article class, 10pt
\textrm{..} or \rmfamily | family | cmr
\textsf{..} or \sffamily | family | cmss
\texttt{..} or \ttfamily | family | cmtt
\textmd{..} or \mdseries | series | m
\textbf{..} or \bfseries | series | bx
\textup{..} or \upshape | shape | n
\textit{..} or \itshape | shape | it
\textsl{..} or \slshape | shape | sl
\textsc{..} or \scshape | shape | sc
\tiny | size | 5pt
\scriptsize | size | 7pt
\footnotesize | size | 8pt
\small | size | 9pt
\normalsize | size | 10pt
\large | size | 12pt
\Large | size | 14.4pt
\LARGE | size | 17.28pt
\huge | size | 20.74pt
\Huge | size | 24.88pt

The low-level commands used to change font attributes are as follows.

\fontencoding{encoding}

\fontfamily{family}

\fontseries{series}

\fontshape{shape}

\fontsize{size}{baselineskip}

Each of these commands sets one of the font attributes; \fontsize also sets \baselineskip. The actual font in use is not altered by these commands, but the current attributes are used to determine which font to use after the next \selectfont command.

\selectfont selects a text font, based on the current values of the font attributes. There must be a \selectfont command immediately after any settings of the font parameters by (some of) the five \font<parameter> commands, before any following text. For example, it is legal to say:

   \fontfamily{ptm}\fontseries{b}\selectfont Some text.

to select bold Times Roman, but it is not legal to say:

   \fontfamily{ptm} Some \fontseries{b}\selectfont text.

\usefont{encoding}{family}{series}{shape}

is short hand for the equivalent \font... commands followed by\selectfont.


Environments

Some examples of how to use environments are given here.

  • Alignments

  • Listing Items
  • Tabular
  • Array
  • Pictures
  • Maths
  • Figures
  • Tabbing
  • Verbatim
  • Quote, abstract
  • Letter
  • Curriculum Vitae


Alignments

In these environments \\ starts a new line.

\begin{flushleft}
Some people like to stay firmly\\ on the left whereas others
\end{flushleft}
\begin{flushright}
feel more at home on the right.\\
\end{flushright}
\begin{center}
but most of us prefer to stay dead in the center.
\end{center}

Some people like to stay firmly
on the left whereas others

feel much more at home
on the right.

but most of us prefer to stay dead in the center.


Listing Items

The items can be marked in one of three way:

\begin{itemize}
\item just by a bullet, using \texttt{itemize}

\item numbered, using \texttt{enumerate}

\begin{enumerate}
\item one
\item two
\item three
\end{enumerate}

\item or with a label, using \texttt{description}

\begin{description}
\item[itemize] bullets
\item[enumerate] automatic numbering
\item[description] labelling
\end{description}

\end{itemize}

  • just by a bullet, using itemize

  • numbered, using enumerate

    1.

    one

    2.

    two

    3.

    three

  • or with a label, using description

    itemize

    bullets

    enumerate

    automatic numbering

    description

    labelling

The pifont package includes a variant of the itemize command that will replace the usual 'bullet' by a Zapf Dingbat symbol of your choice

\begin{dinglist}{43}
\item First
\item Second
\end{dinglist}

and a variant of the enumerate command that given an initial Zapf Dingbat symbol will increment the symbol for each item.

\begin{dingautolist}{172}
\item First
\item Second
\end{dingautolist}


Tabular

Tabular output is supported. When you create the environment you specify how many columns to have and how the contents are to be aligned (use l, c or r to represent each column with either left, center or right alignment) and where you want vertical lines (use |). The contents of the columns are separated by a `&' and rows by \\. Here's a simple example

\begin{tabular}{l|c|r}
left & centre & right\\
more left & more centre & more right\\
\end{tabular}

left | centre | right
more left | more centre | more right

To draw a full horizontal line, use \hline otherwise draw a line across selected columns using \cline. The \multicolumn command allows items to span columns. It takes as its first argument the number of columns to span. The following, more complicated example shows how to use these facilities.

\begin{tabular}{||l|lr||} \hline
\textbf{Veg}  & \multicolumn{2}{|c||}{\textbf{Detail}}\\\hline
carrots    & per pound & \pounds 0.75 \\ \cline{2-3}
           & each      &         20p  \\ \hline
mushrooms  & dozen     &         86p  \\ \cline{1-1} \cline{3-3}
toadstools & pick your own & free     \\ \hline
\end{tabular}

Veg | Detail
carrots | per pound | £0.75
 | each | 20p
mushrooms | dozen | 86p
toadstools | pick your own | free

Tables won't continue on the next page if they're too long. The longtable or supertabular commands are needed to do this. See the Supertabular document for details and examples.

If the text in a column is too wide for the page, LATEX won't automatically text-wrap. Using p{5cm} instead of c, l or r in the tabular line will wrap-around the text in a 5 cm wide column.

There are various packages to assist with table creation. The array package adds some helpful features, including the ability to add formatting commands that control a whole column at a time, like so

\begin{tabular}{>{\ttfamily}l>{\scshape}c>{\Large}r}
      Text  & More Text & Large Text\\
      Left  & Centred   & Right
\end{tabular}

Text | MORE TEXT | Large Text
Left | CENTRED | Right

The rotating package is useful if you have a wide table that you want to display in landscape mode. You need to put your table inside \begin{sidewaystable} and \end{sidewaystable}.

If you want the table to have a caption and float (float up the page if it's started right near the foot of a page, for example), use

\begin{table}[htbp]
\begin{tabular}...
...
\end{tabular}
\caption{...}
\end{table}

See section 4.7 for details.


Array

The array environment (not to be confused with the array package) is similar to the tabular but must be within a math environment. This

\begin{math}
\left(
\begin{array}{clrr}
      a+b+c & uv & x-y & 27 \\
       x+y  & w  & +z  & 363
\end{array}
\right)
\end{math}

produces


Pictures

LATEX has some graphics capabilities. It's much better to import an encapsulated postscript file. See the LaTex Maths and Graphics document for more details.

\newcounter{cms}
\setlength{\unitlength}{1mm}
\begin{picture}(50,39)
\put(0,7){\makebox(0,0)[bl]{cm}}
\multiput(10,7)(10,0){5}{\addtocounter
   {cms}{1}\makebox(0,0)[b]{\arabic{cms}}}
\put(15,20){\circle{6}}
\put(30,20){\circle{6}}
\put(15,20){\circle*{2}}
\put(30,20){\circle*{2}}
\put(10,24){\framebox(25,8){a box}}
\put(10,32){\vector(-2,1){10}}
\multiput(1,0)(1,0){49}{\line(0,1){2,5}}
\multiput(5,0)(10,0){5}{\line(0,1){3,5}}
\thicklines
\put(0,0){\line(1,0){50}}
\multiput(0,0)(10,0){6}{\line(0,1){5}}
\end{picture}


Maths

Maths is dealt with in the LaTex Maths and Graphics document. Here are some examples

\begin{math}
 \lim_{n \rightarrow \infty}x = 0 \\
x^{2y} \\
x_{2y} \\
x^{2y}_{1} \\
\frac{x+y}{1 + \frac{1}{n+1}} \\
\end{math}

produces


Figures

To include graphics, use the \includegraphics command (provided by the graphicx package) inside figure environment. The arguments to figure specify where the space will be made, preferentially

h | here
t | top of page
b | bottom of page
p | on a page with no text

\begin{figure}[htbp]
   \vspace{1cm}
   \caption{1 cm of space}
\end{figure}

Figure 1: 1 cm of space

Putting ! as the first argument in the square brackets will encourage LATEX to do what you say, even if the result's sub-optimal.

If you have a label defined in the caption, LATEX may give an error message. \label is a fragile command (see the LATEX book for details) so you'll need to do something like

...
\caption{1 cm of space\protect\label{EMPTY}}

or simply put the \label command after the caption. Note that if you put the \label before the caption, the resulting reference will be the section number and not the figure number. See the LATEX Maths and Graphics document for more details.


Tabbing

Within this environment tabs can be set by \= and the next tab moved to by using \.

\begin{tabbing}
if \= it's raining\\      % set tab here, after the 'if'
   \> get an umbrella \=\\ % go to the defined tab and set a new one
else\\
   \> get wet \> * next tab is here\\
endif
\end{tabbing}

if it's raining

       get an umbrella
 else

get wet  * next tab is here

endif


Verbatim

Within this environment things come out unformatted. It's useful for showing examples of typed input and provides a way of printing characters that have a special meaning for LATEX.

\begin{tex2html_preform}verbatim46#\end{tex2html_preform}

produces

caret is ^, tilde is ~ and backslash is \

If you just want to quote a few characters, use \verb|quoted text|. The characters delimiting the quote can be anything as long as they are the same.


Quote, abstract

These widen the margins and change the font. The abstract environment also adds a title.


Letter

See letter.tex in /export/Examples/LaTeX


Curriculum Vitae

See cv.tex in /export/Examples/LaTeX


Customising

  • Macros

  • Modifications
  • New Commands
  • Packages
  • An Example


Macros

At the top of the source of this file is

\def\xdt{$\cal X\!\!$\texttt{.desktop}}

which defines \xdt to be [image] .desktop. Using such constructions can make your document much tidier, and saves on typing.


Modifications

Many of the features of a LATEX document are easily customised, but you'll often have to look at the class (.cls) files to find out what to do. For example, suppose you wanted to have References in a book rather than Bibliography. If you look in book.cls you'll see

   \newcommand\bibname{Bibliography}

so adding

   \renewcommand{\bibname}{References}

to your file should achieve what you want.

Counters (e.g. figure) have related commands (e.g. thefigure) to control their appearance, so they're easy to customise

   \renewcommand\thefigure{\roman{figure}}

produces figure numbers in lower case roman numerals. Longer commands can be adapted too. Remember however, that if the command involves a @ you have to enclose your changes in \makeatletter ... \makeatother. Here's an example that changes the appearance of section headings -

\makeatletter
\renewcommand{\section}{\@startsection{section}{1}{0mm}
{\baselineskip}%
{\baselineskip}{\normalfont\normalsize\scshape\centering}}%
\makeatother
\begin{document}


New Commands

A completely new command can be created using

\newcommand{\ commandname[number of arguments]{ command text, using #1, #2 etc to denote arguments}

For example,

\newcommand{\ve}[1]{\(#1_1 ... #1_n\)}
\ve{x}

produces as output x1 ... xn

A problem with this example is that it shouldn't change to math mode if LATEX is already in that mode. A better try would be

\newcommand{\ve}[1]{\ensuremath{#1_1 ... #1_n}}

which will only change to math mode if it's necessary.

A new environment is just as easily created - give the name of the environment, and what you want to happen on entering and leaving the environment. The following provides a variant of the itemize command.

\newenvironment{emlist}{\begin{itemize} \em}{\end{itemize}}
\begin{emlist}
\item first comment
\item second comment
\end{emlist}
The end of the environment ends the scope of the emphasis.

  • first comment

  • second comment

The end of the environment ends the scope of the emphasis.


Packages

There are many features and options not mentioned in this handout. See the packages section of the online LATEX page for more details. You can often find out what you want by looking at the files in the system directories. If your file begins

\documentclass[12pt]{article}

then various macro files are read when you run latex, namely (article.cls and size12.sty). Some of these files are well-enough commented to be useful documentation.


An Example

minipage creates a miniature page complete with its own footnotes etc. It can be created to any set width. Footnotes within a minipage use a different counter to other footnotes1. This example ensures that all the numbers follow on in sequence. The footnotes in minipages are marked by letters rather than numbers, so here the type is changed to arabic.

\begin{minipage}{\textwidth}
% Set the minipage footnote counter
\setcounter{mpfootnote}{\value{footnote}}
% Redefine the command that produces the footnote number
\renewcommand{\thempfootnote}{\arabic{mpfootnote}}
\begin{tabular}{|ll|}\hline
one & two\footnote{A minipage footnote}\\\hline
\end{tabular}
\setcounter{footnote}{\value{mpfootnote}}
\end{minipage}

one

two1

1 A minipage footnote

You might find this trick useful if you want footnotes in tables. They don't come out otherwise.2

Here's an example of using a package. The multicol file lets one change the number of columns easily. To switch into 3-column text use

\begin{multicols}{3}{
Put the text here. Maths, tables, pictures etc are all ok, but not
figures. But you have to remember to load in the \texttt{multicol}
package at the top of your document.
}
\end{multicols}

Put the text here. Maths, tables, pictures etc are all ok, but not figures. But you have to remember to load in the multicol package at the top of your document. LATEX uses the value of the environmental variable TEXINPUTS to decide where to look for sty files. If you create a directory called (say) inputs, copy a system *.sty file into it and do

export TEXINPUTS=inputs:/opt/latex/inputs:.

then your copy will be read in preference to the system one and you can customise easily.


foot205

... this1

I told you so.


foot608

... this1

I told you so.


foot624

... otherwise.2

Not for me anyway


Footnotes

... this1

I told you so.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

... footnotes1

like this one

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

... otherwise.2

Not for me anyway

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.


LATEX maths and graphics

Tim Love

August 5, 1999

This handout assumes that you have already read the Advanced LaTex document handout, so if you're unsure about `environments', read no further. LATEX produces maths text well, but graphic support is less good. Fortunately there's a graphics editor called xfig whose output can be used in a LATEX file.

Note that there's an alternative way of producing maths in LATEX - [image] -LATEX

  • Maths

    • Environments
    • Special Characters
      • Greek
      • Miscellaneous
      • Arrows
      • Calligraphic
      • Character Modifiers
      • Common functions
    • Subscripts and superscripts
    • Overlining, underlining and bold characters
    • Roots
    • Fractions
    • Delimiters
    • Numbering and labelling
    • Matrices
    • Macros
    • Packages
    • Fine tuning
    • Maths and Postscript fonts
    • Matlab and LaTeX
    • Examples
  • Graphics
    • Postscript
      • psfrag: adding maths to postscript files
      • Postscript from PCs/Macs
    • Scaling, rotation, clipping, wrap-around and shadows
    • GIF and jpeg files
    • Bitmaps
    • Graphs


Maths

There's more to maths typesetting than meets the eye. Many conventions used in the typesetting of plain text are inappropriate to maths. LATEX goes a long way to help you along with the style. For example, in a LATEX maths environment, letters come out in italics, `-' as `-' (minus) instead of the usual `-' (dash), `*' becomes *, ' becomes ' and spacing is changed (less around `/', more around `+').

Many of the usual LATEX constructions can still be used in maths environments but their effect may be slightly different; eg \textbf{ } only affects letters and numbers. `{' and `}' are still special characters; they're used to group characters.

As usual in LATEX you can override the defaults, but think before doing it: maths support in LATEX has been carefully thought out and is quite logical though the LATEX source text may not be very readable. It's a good idea to write out the formulae on paper before you start LATEXing, and try not to overdo the use of the `\frac' construction; use `/' instead.

  • Environments

  • Special Characters
    • Greek
    • Miscellaneous
    • Arrows
    • Calligraphic
    • Character Modifiers
    • Common functions
  • Subscripts and superscripts
  • Overlining, underlining and bold characters
  • Roots
  • Fractions
  • Delimiters
  • Numbering and labelling
  • Matrices
  • Macros
  • Packages
  • Fine tuning
  • Maths and Postscript fonts
  • Matlab and LaTeX
  • Examples


Environments

There are 2 environments to display one-line equations.

equation:-

Equations in this environment are numbered.

\begin{equation}
 x + iy
\end{equation}

x + iy

(1)

displaymath:-

These won't be numbered. \[, \] can be used as abbreviations for \begin{displaymath} and \end{displaymath}.

\begin{displaymath}
 x + iy
\end{displaymath}

x + iy

Never leave a blank line before these equations; it starts a new paragraph and looks ugly. '\displaystyle' is the font type used to print maths in these display environments. Other relevant environments are:-

math:-

For use in text. \( and \) can be used to delimit the environment, as can the TEX constructions $ and $ . For example, $x=y^2$ gives x=y2.

eqnarray:-

This is like a 3 column tabular environment. Each line by default is numbered. You can use the eqnarray* variant to suppress numbering altogether.

\begin{eqnarray}
a1 & = & b1 + c1\nonumber\\
a2 & = & b2 - c2
\end{eqnarray}

a1

=

b1 + c1

a2

=

b2 - c2

(2)

Maths in these 2 sorts of environments have different default sizes for some characters and other behavioural differences so that a line of maths won't impinge on text lines below or above. If you want to put some non-maths text in amongst maths then enclose it in an \mbox{...}.


Special Characters

  • Greek

  • Miscellaneous
  • Arrows
  • Calligraphic
  • Character Modifiers
  • Common functions


Greek

\alpha | \beta | \gamma | \delta |  | \epsilon
\zeta | \eta | \theta | \iota |  | \kappa
\lambda | \mu | \nu | \xi | o | o
\pi | \rho | \sigma | \tau |  | \upsilon
\phi | \chi | \psi | \omega |  | \Gamma
\Delta | \Theta | \Lambda | \Xi |  | \Pi
\Sigma | \Upsilon | \Phi | \Psi |  | \Omega


Miscellaneous

\ldots | \cdots | \vdots
\ddots | \pm | \mp
\times | \div | \ast
\star | \circ | \bullet
\cdot | \cap | \bigcap
\cup | \bigcup | \uplus
\biguplus | \sqcap | \sqcup
\bigsqcup | \vee | \bigvee
\wedge | \bigwedge | \setminus
\wr | \diamond | \bigtriangleup
\bigtriangledown | \triangleleft | \triangleright
\oplus | \bigoplus | \ominus
\otimes | \bigotimes | \oslash
\odot | \bigodot | \bigcirc
\amalg | \leq | \prec
\preceq | \ll | \subset
\subseteq | \sqsubseteq | \in
\vdash | \geq | \succ
\succeq | \gg | \supset
\supseteq | \sqsupseteq | \ni
\dashv | \equiv | \sim
\simeq | \asymp | \approx
\cong | \neq | \doteq
\propto | \models | \perp
\mid | \parallel | \bowtie
\smile | \frown | \aleph
\hbar | \imath | \jmath
\ell | \wp | \Re
\Im | \prime | \empty
\nabla | \surd | \top
\bot | \| | \angle
\forall | \exists | \neg
\flat | \natural | \sharp
\backslash | \partial | \infty
\triangle | \sum | \prod
\coprod | \int | \oint


Arrows

\leftarrow | \Leftarrow | \rightarrow
\Rightarrow | \leftrightarrow | \Leftrightarrow
\mapsto | \hookleftarrow | \leftharpoonup
\leftharpoondown | \rightleftharpoons | \longleftarrow
\Longleftarrow | \longrightarrow | \Longrightarrow
\longleftrightarrow | \Longleftrightarrow | \longmapsto
\hookrightarrow | \rightharpoonup | \rightharpoondown
\uparrow | \Uparrow |
\downarrow | \Downarrow | \updownarrow
\nearrow | \searrow | \swarrow
\nwarrow |  |


Calligraphic

These characters are available if you use the \cal control sequence.

${\cal A B C D E F G H I J K L M N O P Q R S T U V W X Y Z}$

gives


Character Modifiers

\hat{e} | \widehat{easy}
\tilde{e} | \widetilde{easy}
\check{e} | \breve{e}
\acute{e} | \grave{e}
\bar{e} | \vec{e}
\dot{e} | \ddot{e}
\not e |

Note that the wide versions of hat and tilde cannot produce very wide alternatives. The `\not' operator hasn't properly cut the following letter. The Fine Tuning section on page [*] describes how to adjust this.

If you want to place one character above another, you can use \stackrel, which prints its first argument in small type immediately above the second

$ a \stackrel{def}{=} b + c $

gives

See the Macros section for how to stack characters using atop.


Common functions

In a maths environment, LATEX assumes that variables will have single-character names. Function names require special treatment. The advantage of using the following control sequences for common functions is that the text will not be put in math italic and subscripts/superscripts will be made into limits where appropriate.

\arccos | \arcsin | \arctan | \arg | \cos | \cosh | \cot
\coth | \csc | \deg | \det | \dim | \exp | \gcd
\hom | \inf | \ker | \lg | \lim | \liminf | \ln
\log | \max | \min | \Pr | sec | \sin | \sinh
\sup | \tan | \tanh |  |  |  |


Subscripts and superscripts

These are introduced by the `^' and `_' characters. Depending on the base character and the current style, the sub- or superscripts may go to the right of or directly above/below the main character. With letters it goes to the right.

$F_2^3$

produces `F23'. Note that the sub- and superscripts aren't in line. To make them so, you can add an invisible character after the `F'. $F{}_2^3$ produces F23.

With [image] the default behaviour is different in display and text styles.

$\sum_{i=0}^2 $

produces [image] (text style) but

\[\sum_{i=0}^2 \]

produces (in display style)

This default behaviour can be overridden, if you really need to. For example in text mode,

$\sum\limits_{i=0}^2$

produces


Overlining, underlining and bold characters

$\underline{one} \overline{two}$

produces [image]. This is not a useful facility if it's used more than once on a line. The lines are produced so that they don't quite overlap the text; lines over or under different words won't in general be at the same height.

To be able to reproduce bold maths, it's best to use the bm package. $E = \bm{mc^2}$ produces E = mc2.

Alternatively, you can use \mathbf{} to create bold characters - $\mathbf{F}_2^3$ produces F23. or you can use the following idea

\usepackage{amsbsy} % This loads amstext too
\begin{document}
$\omega + \boldsymbol{\omega}$

% Use the following if whole expressions need to be in bold
{\boldmath $\omega $}
\end{document}


Roots

$\sqrt{4} + \sqrt[3]{x + y}$

gives [image].


Fractions

Three constructions for putting expressions above others are

frac:-

$\frac{1}{(x + 3)}$ produces [image].

choose:-

${n + 1 \choose 3}$ produces [image].

atop:-

${x \atop y}$ produces [image].

These constructions can be used with ones described earlier. E.g.,

\[ \sum_{-1\le i \le 1 \atop 0 < j < \infty} f(i,j)\]

gives


Delimiters

these | are made by these | and these | are made by these
( | ( | ) | )
[ | [ | ] | ]
 | \{ |  | \}
 | \lfloor |  | \rfloor
 | \lceil |  | \rceil
 | \langle |  | \rangle
/ | / |  | \backslash
| | | |  | \|
 | \uparrow |  | \Uparrow
 | \downarrow |  | \Downarrow
 | \updownarrow |  | \Updownarrow

This table shows the standard sizes. To get bigger sizes, use these prefices

(for left delimiters) | (for right delimiters) | magnification
\bigl | \bigr | a bit bigger, but won't overlap lines
\Bigl | \Bigr | 150% times big
\biggl | \biggr | 200% times big
\Biggl | \Biggr | 250% times big

For example,

$\Biggl\{2\Bigl(x(3+y)\Bigr)\Biggr\}$

gives [image]. If you're not using the default text size these commands might not work correctly. In that case try the exscale package.

It's preferable to let LATEX choose the delimiter size for you by using \left and \right. These will produce delimiters just big enough for the formulae inbetween.

$\left( frac{(x+iy)}{\{\int x\}} \right)$

gives

The left and right delimiters needn't be the same type. It's sometimes useful to make one of them invisible

\[ z = \left\{
              \begin{array}{ll}
                   1 & (x>0)\\
                   0 & (x<0)
              \end{array}
       \right.
\]

produces

Over- and underbracing works too.

$\overbrace{\alpha \ldots \omega}^{\mbox{greek}}
 \underbrace{a \ldots z}_{\mbox{english}}$

produces [image]. The use of \mbox stops the text appearing in math italic.


Numbering and labelling

Numbering happening automatically when you display equations. If you don't want an equation numbered, use \nonumber beside the equation. Equation numbers appear to the right of the maths by default. To make them appear on the left use the leqno class option (i.e., use \documentclass[leqno,....]{....}).

Use \label{} to label an equation (or figure, section etc) in order to reference from elsewhere.

\begin{equation}
W_{\bf S}(t,\omega) = \int\limits_{-\infty}^{\infty} {
  {\cal R}_{\bf S}(t,\tau) e^{-j\omega\tau} \,d \tau }
\label{LABELLING}
\end{equation}

(3)

Now the following text

 refers back to equation \ref{LABELLING}

refers back to equation 3 by number, and

 refers back to the equation on page \pageref{LABELLING}

refers back to the equation on page [*] .

A file will have to be LATEX'ed twice before the references, both forwards and backwards, will be correctly produced.


Matrices

The array environment is like LATEX's tabular environment except that each element is in math mode. The default font style used is \textstyle but you can override this by changing the \displaystyle.

\begin{math}
\begin{array}{clrr} %
      a+b+c & uv & x-y & 27 \\
       x+y  & w  & +z  & 363
\end{array}
\end{math}

produces

The rows are arranged so that their centres are aligned. You can align their tops or bottoms instead by using a further argument when you create the array.

\begin{array}{clrr}[t]

would produce top-aligned lines, and `[b]' would produce bottom-aligned ones. The Delimiters section of this document shows how to bracket matrices.

TEX has a few maths facilities not mentioned in the LATEX book. The following TEX construction might be useful.

\begin{math}
\bordermatrix{&a_1&a_2&...&a_n\cr
          b_1 & 1.2  & 3.3  & 5.1  & 2.8  \cr
          c_1 & 4.7  & 7.8  & 2.4  & 1.9  \cr
          ... & ...  & ...  & ...  & ...  \cr
          z_1 & 8.0  & 9.9  & 0.9  & 9.99  \cr}
\end{math}


Macros

These aid readability, save on repetitive typing and offer ways of producing stylistic variations on standard LATEX formats.

\def\bydefn{\stackrel{def}{=}}
\def\convf{\hbox{\space \raise-2mm\hbox{$\textstyle
    \bigotimes \atop \scriptstyle \omega$} \space}}

produce [image] and [image] when $\bydefn$ and $\convf$ are typed.


Packages

The following packages may be of help

  • easybmat - easy block matrices

  • easyeqn - easy equations.

  • easymat - easy matrices

  • easytable - easy tables

  • easyvector - easy vectors

  • delarray - nested arrays

  • theorem - gives more choice in theorem layout

  • subeqnarray - Renumbering of sub-arrays in math-mode

  • subeqn - Different numbering sub-arrays


Fine tuning

It's generally a good idea to keep punctuation outside math mode; LATEX's normal handling of spacing around punctuation is suspended during maths. Sometimes you might want to adjust the spacing in a formula (e.g., you might want to add space before dx). Use these symbols :-

a\, b | ( [image] ) thin space
a\ b | ( [image] ) medium space
a\; b | ( [image] ) thick space
a\! b | ( [image] ) negative thin space

Long math expressions aren't broken automatically unless you use the breen package, which is still a little experimental. In an eqnarray environment you may want to break a long line manually. You can do this by puttingt

y & = & a + b \nonumber \\
  &   & + k

to give

y | = | a + b |
 |  | + k | (4)

but the spacing around the `+' on the 2nd line is wrong because LATEX thinks it's a unary operator. You can fool LATEX into treating it as a binary operator by inserting a hidden character.

y & = & a + b \nonumber \\
  &   & \mbox{} + k

gives

y | = | a + b |
 |  |  | (5)

You can use the \lefteqn construction to format long expressions so that continuation lines are differently indented.

\begin{eqnarray}
\lefteqn{x+ iy=}\\
 & & a + b + c + d + e + f + g + h + i + j + k +\nonumber\\
 & & l + m \nonumber
\end{eqnarray}

x+ iy=
 | a + b + c + d + e + f + g + h + i + j + k +
 | l + m

If you want more vertical spacing around a line you can create an invisible vertical "struct" in LaTeX. \rule[-.3cm]{0cm}{1cm} creates a box of width 0, height 1cm which starts .3cm below the usual line base. By adjusting these values you should be able to create as much extra space below/above the maths as you like. and is created by

$A \over B$  \rule[-.3cm]{0cm}{1cm}{and}


Maths and Postscript fonts

It's easy to use a postscript font (like helvetica) for the text of a LATEX document. What's harder is using the same font for maths. An easy, reasonable option is to use the mathptm package to put the maths into the postscript Times font.


Matlab and LaTeX

Matlab has some support for LaTeX production. For example

  latex('(sin(x)+2*x+3*x^2)/(5*x+6*x^2)','math.tex')

puts the LaTeX representation of the expression into a file called math.tex. Type ``help latex" inside matlab for details.


Examples

  •
    • \begin{equation}
    \hat{\theta}_{w_i} = \hat{\theta}(s(t,{\cal U}_{w_i})).
    \end{equation}

    gives

    (7)

  •
    • \begin{eqnarray}
    {\cal M}^2(\hat{\theta},\theta) &=& E[(\hat{\theta} - \theta)^2]
    \nonumber \\
    {\cal M}^2(\hat{\theta},\theta) &=& {\rm var}^2(\hat{\theta}) +
    {\cal B}^2(\hat{\theta}).
    \end{eqnarray}

    gives

    = |
= | (8)

  •
    • \begin{equation}
    \hat{W}_{s}(t,\omega;\phi) \bydefn
    \int\limits_{-\infty}^{\infty}
    {\hat{\cal R}_s(t,\tau;\psi) e^{-j\omega \tau}
    \, d \tau }
    \end{equation}

    gives

    (9)

  •
    • \begin{eqnarray}
    {\cal B}(t,\omega) & \approx &
    {1 \over 4\pi}
    {\cal D}_t^2 W_{\bf S}(t, \omega)
    {{{\scriptstyle \infty} \atop
    {\displaystyle \int \! \int \!
    }}\atop {\scriptstyle -\infty}}
    t_1^2
    \phi(t_1,\omega_1) \, dt_1 d\omega_1
    \nonumber \\
    && +
    {1 \over 4\pi}
    {\cal D}_\omega^2 W_{\bf S}(t, \omega)
    {{{\scriptstyle \infty} \atop
    {\displaystyle \int \! \int \!
    }}\atop {\scriptstyle -\infty}}
    \omega_1^2
    \phi(t_1,\omega_1) \, dt_1 \, d\omega_1.
    \label{F4}
    \end{eqnarray}

    gives

    (10)

  •
    • \newsavebox{\DERIVBOXZLM}
    \savebox{\DERIVBOXZLM}[2.5em]{$\Longrightarrow\hspace{-1.5em}
    \raisebox{.2ex}{*}
    \hspace{-.7em}\raisebox{-.8ex}{\scriptsize lm}\hspace{.7em}$}
    \newcommand{\Deriveszlm}{\usebox{\DERIVBOXZLM}}

    \Deriveszlm

    gives


Graphics

LATEX has a picture environment in which pictures can be drawn, but you'll find graph paper handy. xfig can create code for the picture environment but the resulting graphics still suffer several limitations: only certain slopes and circles can be reproduced. The best method presently available on Unix is to use xfig to produce postscript files, which have no such limitations, but require a postscript printer or equivalent.

Whatever graphics you want to add, you should use the figure environment so that LATEX can cope sensibly with situations where, for example, you attempt to insert near the bottom of a page a graphic that's half a page high. The figure environment will float the graphic to the top or bottom of the page, or on the next page, with preferences that you can provide.

h | here
t | top of page
b | bottom of page
p | on a page with no text

Putting ! as the first argument in the square brackets will encourage LATEX to do what you say, even if the result's sub-optimal.

\begin{figure}[htbp]
   \vspace{0.5in}
   \caption{0.5 inch of space}
\end{figure}

Figure 1: 0.5 inch of space

It's possible to have more than one graphic in a figure. See the example later on.

  • Postscript

    • psfrag: adding maths to postscript files
    • Postscript from PCs/Macs
  • Scaling, rotation, clipping, wrap-around and shadows
  • GIF and jpeg files
  • Bitmaps
  • Graphs


Postscript

It's easy to incorporate Postscript files as long as they have a proper bounding box comment; i.e. LATEX requires full Encapsulated Postscript as produced by (for example) xv and xfig on the HPs. If the file hasn't got a BoundingBox line near the top, you can use ps2epsi to generate one. Wherever the postscript file comes from, simply use

\documentclass[dvips]{article}
\usepackage{graphicx}

then include the postscript file using the following commands

\begin{figure}[htbp]
\includegraphics{yourfile.ps}
\end{figure}

LATEX can cope with compressed postscript files too. The following works

\begin{figure}[htbp]
\includegraphics{yourfile.ps.gz}
\end{figure}

Just about all of the following facilities use postscript. You'll need to run latex to generate `foo.dvi'. This file can be viewed by the latest xdvi program, which can cope with embedded postscript. Run dvips -o foo.ps foo.dvi to convert the resulting DVI/postscript file to pure postscript. This will produce a file that can be previewed with ghostview or gs. On the teaching system this file can be printed out using plotview or

  lp -dljmr1 -opostscript foo.ps

  • Postscript from PCs/Macs


psfrag: adding maths to postscript files

Many packages that produce postscript output don't provide good maths facilities. It's often easier to add the maths in later using the psfrag package. This lets you replace text in a postscript file (produced with xfig, matlab, etc) by a fragment of LATEX. See the online documentation for details.


Postscript from PCs/Macs

Modern applications should generate a conforming EPS file. Under windows when you're printing to file, look at the PostScript properties, and choose at the top of the window either 'Archive Format' or 'Encapsulated PS' or 'Optimize for Portability'. If you have problems on a Macintosh, check that you're using the LaserWriter 8 driver. Platform-specific considerations do crop up. The EPS generated on the Macintosh will use ASCII 13 line terminators, while Unix will use ASCII 10 (and DOS will use both). If this causes trouble, use emacs to convert, or try (in Unix)

     tr "\015" "\012" <original.ps >new.ps


Scaling, rotation, clipping, wrap-around and shadows

To scale, use some optional arguments

   \includegraphics[width=5cm,height=10cm]{yourfile.ps}

would rescale the postscript so that it was 5cm wide and 10cm high. To make the picture 5cm wide and scale the height in proportion use

   \includegraphics[width=5cm]{yourfile.ps}

To rotate anticlockwise by the specified number of degrees, use

   \includegraphics[angle=150]{yourfile.ps}

The following examples demonstrate how to combine these features and how to use the subfigure package to have more than one graphic in a figure.

Figure 2: Tigers

\begin{figure}[hbtp]
  \includegraphics[height=40mm]{/export/ghostfonts/tiger.eps}
  \includegraphics[angle=120, height=20mm]{/export/ghostfonts/tiger.eps}
\caption{Tigers}
\end{figure}

% remember to do \usepackage{subfigure} at the top of the document!
\begin{figure}[hbtp]
\begin{center}
% an mbox for alignment
\mbox{\subfigure[Small]
{\includegraphics[height=30mm]{/export/ghostfonts/crest.eps}}\quad
\subfigure[Medium]
{\includegraphics[height=40mm]{/opt/latex/ps/color_CU_arms.ps}}\quad
\subfigure[Large]
{\includegraphics[height=50mm]{/export/ghostfonts/crest.eps}}
}% end of mbox
\caption{3 crests}
\end{center}
\end{figure}

Figure 3: 3 crests

[Small] [image] [Medium] [image] [Large]

To clip the postscript image use the viewpoint argument. The following fragment would display only part of the image. The viewport coordinates are in the same units as the bounding box.

\begin{figure}[htbp]
\includegraphics[viewport=200 400 400 600,width=5cm,clip]%
{/opt/latex/ps/color_CU_arms.ps}
\end{figure}

% Use the floatflt package
\begin{floatingfigure}[l]{4cm}
\includegraphics[width=2cm]{/export/ghostfonts/crest.eps}
\caption{Using floatingfigure}
\end{floatingfigure}

Figure 4: Using floatingfigure

4cm

The floatflt package lets you insert a graphic and have the text wrap around it. You can provide 2 arguments to the floatingfigure command: the first (l or r) selects whether you want the graphic to be on the left or right of the page. The 2nd argument gives the width of the graphic. Not all text will flow perfectly around (for example, verbatim text fails) so check the final output carefully.

Using the fancybox package gives you access to \shadowbox, \ovalbox, \Ovalbox and \doublebox commands, which can be used with text or with graphics. For example, \shadowbox{shadow package} produces shadow package and

\ovalbox{\includegraphics[height=10mm]{/opt/latex/ps/color_CU_arms.ps}}

produces [image]. Unfortunately, the fancybox package as supplied suppresses the table of contents. The locally produced contentsfancybox solves this, but may introduce graphics problems.


GIF and jpeg files

CUED users can include a file called keyboard.gif, for example, by doing gif2ps -b keyboard.gif (as long as you don't change the GIF file you need only do this once) and then including the GIF file as you would a postscript one.

For JPEG files run "jpeg2ps -h file.jpg > file.eps" then include the postscript file in the usual way. The resulting eps file will be little bigger than the original file. Alternatively, if you put the 'Bounding Box' line from the eps file and put it in file.jpg.bb you can include JPEG files in the same way that you do postscript files.


Bitmaps

If you want to include a small X11 bitmap into your document, you can use the Bitmap macro.

\usepackage{bitmap}
\begin{document}
\Bitmap{/usr/local/include/X11/bitmaps/cued_icons/kettle.px}{1pt}
Now in a frame
\vspace{.5cm}
\fbox{\vbox{\Bitmap{/usr/local/include/X11/bitmaps/cued_icons/xpc.px}{1pt}}}
\end{document}

/usr/local/include/X11/bitmaps/cued_icons/kettle.px1pt Now in a frame


Graphs

Probably the easiest way to put complicated graphs into LATEX is to use gnuplot or Matlab, and produce encapsulated postscript output.

The ebar package (a local version of the bar package) is ok for simpler graphs. See The LATEX Companion for more details.

\begin{center}
\textbf{CUED Gopher Usage, 1994}

\begin{figure}[htbp]
\begin{barenv}
% set the 'z' axis depth
\setdepth{10}
%Scale the height
\setstretch{.01}
% Put the numbers above the bars. Other options include 'empty',
\setnumberpos{up}
% Set type of x labels (numbers by default) but could also be 'days'
\setxvaluetyp{month}
% Set the x origin, end, and step size
\setxaxis{1}{3}{1}\setxname{Activity}
% Set the y origin, end, and step size
\setyaxis{0}{10000}{1000}\setyname{Accesses}
\ebar{6768}{1}
\ebar{9917}{2}
\ebar{8306}{3}
\end{barenv}
\end{figure}
\end{center}

CUED Gopher Usage, 1994