LaTeX for scientific documentation

Experimental html version of downloadable textbook, see https://www.tacc.utexas.edu/~eijkhout/istc/istc.html
\[ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% This text file is part of the source of %%%% `Introduction to High-Performance Scientific Computing' %%%% by Victor Eijkhout, copyright 2012-2020 %%%% %%%% mathjax.tex : macros to facility mathjax use in html version %%%% %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \newcommand\inv{^{-1}}\newcommand\invt{^{-t}} \newcommand\bbP{\mathbb{P}} \newcommand\bbR{\mathbb{R}} \newcommand\defined{ \mathrel{\lower 5pt \hbox{${\equiv\atop\mathrm{\scriptstyle D}}$}}} \newcommand\macro[1]{$\langle$#1$\rangle$} \newcommand\dtdxx{\frac{\alpha\Delta t}{\Delta x^2}} \] 34.1 : The idea behind LaTeX, some history of TeX
34.1.1 : Installing LaTeX
34.1.2 : Running LaTeX
34.2 : A gentle introduction to LaTeX
34.2.1 : Document structure
34.2.2 : Some simple text
34.2.3 : Math
34.2.4 : Referencing
34.2.5 : Lists
34.2.6 : Source code and algorithms
34.2.7 : Graphics
34.2.8 : Bibliography references
34.2.9 : Environment variables
34.3 : A worked out example
34.3.1 : Listings
34.3.2 : Native graphing
34.4 : Where to take it from here
34.5 : Review questions
Back to Table of Contents

34 LaTeX for scientific documentation

34.1 The idea behind LaTeX, some history of TeX

crumb trail: > latex > The idea behind LaTeX, some history of TeX

}

TeX is a typesetting system that dates back to the late 1970s. In those days, graphics terminals where you could design a document layout and immediately view it, the way you can with for instance Microsoft Word, were rare. Instead, TeX uses a two-step workflow, where you first type in your document with formatting instructions in an ascii document, using your favorite text editor. Next, you would invoke the latex program, as a sort of compiler, to translate this document to a form that can be printed or viewed.

  %% edit mydocument.tex
  %% latex mydocument
  %% # print or view the resulting output

The process is comparable to making web pages by typing HTML commands.

This way of working may seem clumsy, but it has some advantages. For instance, the TeX input files are plain ascii, so they can be generated automatically, for instance from a database. Also, you can edit them with whatever your favorite editor happens to be.

Another point in favor of TeX is the fact that the layout is specified by commands that are written in a sort of programming language. This has some important consequences:

  • Separation of concerns: when you are writing your document, you do not have to think about layout. You give the `chapter' command, and the implementation of that command will be decided independently, for instance by you choosing a document style.
  • Changing the layout of a finished document is then done by choosing a different realization of the layout commands in the input file: the same `chapter' command is used, but by choosing a different style the resulting layout is different. This sort of change can be as simple as a one-line change to the document style declaration.
  • If you have unusual typesetting needs, it is possible to write new TeX commands for this. For many needs such extensions have in fact already been written; see section  .

The commands in TeX are fairly low level. For this reason, a number of people have written systems on top of TeX that offer powerful features, such as automatic cross-referencing, or generation of a table of contents. The most popular of these systems is LaTeX. Since TeX is an interpreted system, all of its mechanisms are still available to the user, even though LaTeX is loaded on top of it.

34.1.1 Installing LaTeX

crumb trail: > latex > The idea behind LaTeX, some history of TeX > Installing LaTeX

The easiest way to install LaTeX on your system is by downloading the TeX{}live distribution from http://tug.org/texlive . Apple users can also use fink or macports . Various front-ends to TeX exist, such as TeX{}shop on the Mac.

34.1.2 Running LaTeX

crumb trail: > latex > The idea behind LaTeX, some history of TeX > Running LaTeX

Purpose

In this section you will run the LaTeX compiler

Originally, the latex compiler would output a device independent file format, named dvi , which could then be translated to PostScript or PDF, or directly printed. These days, many people use the pdflatex program which directly translates .tex files to .pdf files. This has the big advantage that the generated PDF files have automatic cross linking and a side panel with table of contents. An illustration is found below.

Let us do a simple example.

\documentclass{article}
\begin{document}
Hello world!
\end{document}

FIGURE 34.1: A minimal LaTeX document

Exercise

Create a text file minimal.tex with the content as in figure  . Try the command pdflatex minimal or latex minimal . Did you get a file minimal.pdf in the first case or minimal.dvi in the second case? Use a pdf viewer, such as Adobe Reader, or dvips respectively to view the output.

Caution

{If you make a typo, TeX can be somewhat unfriendly. If you get an error message and TeX is asking for input, typing x usually gets you out, or Ctrl-C . Some systems allow you to type e to go directly into the editor to correct the typo.}

34.2 A gentle introduction to LaTeX

crumb trail: > latex > A gentle introduction to LaTeX

Here you will get a very brief run-through of LaTeX features. There are various more in-depth tutorials available, such as the one by Oetiker  [Oetiker:LaTeXintro] .

34.2.1 Document structure

crumb trail: > latex > A gentle introduction to LaTeX > Document structure

Each LaTeX document needs the following lines:

  \documentclass{ .... } % the dots will be replaced


\begin{document}


\end{document}

The `documentclass' line needs a class name in between the braces; typical values are `article' or `book'. Some organizations have their own styles, for instance `ieeeproc' is for proceedings of the IEEE.

All document text goes between the \verb+ \begin{document} + and \verb+ \end{document} + lines. (Matched `begin' and `end' lines are said to denote an `environment', in this case the document environment.)

The part before \verb+ \begin{document} + is called the `preamble'. It contains customizations for this particular document. For instance, a command to make the whole document double spaced would go in the preamble. If you are using pdflatex to format your document, you want a line

  \usepackage{hyperref}

here.

Have you noticed the following?

  • The backslash character is special: it starts a LaTeX command.
  • The braces are also special: they have various functions, such as indicating the argument of a command.
  • The percent character indicates that everything to the end of the line is a comment.

34.2.2 Some simple text

crumb trail: > latex > A gentle introduction to LaTeX > Some simple text

Purpose

In this section you will learn some basics of text formatting.

Exercise

Create a file first.tex with the content of figure  in it. Type some text in the preamble, that is, before the \n{\ \begin\{document\}} line and run pdflatex on your file.

Outcome

{You should get an error message because you are not allowed to have text in the preamble. Only commands are allowed there; all text has to go after \n{\ \begin\{document\}}.}

Exercise

Edit your document: put some text in between the \n{\ \begin\{document\}} and \n{\ \end\{document\}} lines. Let your text have both some long lines that go on for a while, and some short ones. Put superfluous spaces between words, and at the beginning or end of lines. Run pdflatex on your document and view the output.

Outcome

{You notice that the white space in your input has been collapsed in the output. TeX has its own notions about what space should look like, and you do not have to concern yourself with this matter.}

Exercise

Edit your document again, cutting and pasting the paragraph, but leaving a blank line between the two copies. Paste it a third time, leaving several blank lines. Format, and view the output.

Outcome

{TeX interprets one or more blank lines as the separation between paragraphs.}

Exercise

Add \n{\\usepackage\{pslatex\}} to the preamble and rerun pdflatex on your document. What changed in the output?

Outcome

{This should have the effect of changing the typeface from the default to Times Roman.}

Caution

{Typefaces are notoriously unstandardized. Attempts to use different typefaces may or may not work. Little can be said about this in general.}

Add the following line before the first paragraph:

  \section{This is a section}

and a similar line before the second. Format. You see that LaTeX automatically numbers the sections, and that it handles indentation different for the first paragraph after a heading.

Exercise

Replace article by artikel3 in the documentclass declaration line and reformat your document. What changed?

Outcome

{There are many documentclasses that implement the same commands as article (or another standard style), but that have their own layout. Your document should format without any problem, but get a better looking layout.}

Caution

{The artikel3 class is part of most distributions these days, but you can get an error message about an unknown documentclass if it is missing or if your environment is not set up correctly. This depends on your installation. If the file seems missing, download the files from http://tug.org/texmf-dist/tex/latex/ntgclass/ and put them in your current directory; see also section  .}

34.2.3 Math

crumb trail: > latex > A gentle introduction to LaTeX > Math

Purpose

In this section you will learn the basics of math typesetting

One of the goals of the original TeX system was to facilitate the setting of mathematics. There are two ways to have math in your document:

  • Inline math is part of a paragraph, and is delimited by dollar signs.
  • Display math is, as the name implies, displayed by itself.

Exercise

Put \$x+y\$ somewhere in a paragraph and format your document. Put \n{\ \[ x+y\ \] } somewhere in a paragraph and format.

Outcome

{Formulas between single dollars are included in the paragraph where you declare them. Formulas between \n{\ \[ ...\ \] } are typeset in a display.}

For display equations with a number, use an equation environment. Try this.

Here are some common things to do in math. Make sure to try them out.

  • Subscripts and superscripts: \verb-$x_i^2$-. If the sub or superscript is more than a single symbol, it needs to be grouped: \verb-$x_{i+1}^{2n}$-. If you need a brace in a formula, use \verb-$\{ \}$-.
  • Greek letters and other symbols: \verb-$\alpha\otimes\beta_i$-.
  • Combinations of all these \verb-$\int_{t=0}^\infty tdt$-.

Exercise

Take the last example and typeset it as display math. Do you see a difference with inline math?

Outcome

{TeX tries not to include the distance between text lines, even if there is math in a paragraph. For this reason it typesets the bounds on an integral sign differently from display math.}

34.2.4 Referencing

crumb trail: > latex > A gentle introduction to LaTeX > Referencing

Purpose

In this section you will see TeX's cross referencing mechanism in action.

So far you have not seen LaTeX do much that would save you any work. The cross referencing mechanism of LaTeX will definitely save you work: any counter that LaTeX inserts (such as section numbers) can be referenced by a label. As a result, the reference will always be correct.

Start with an example document that has at least two section headings. After your first section heading, put the command \verb+ +, and put \verb+ + after the second section heading. These label commands can go on the same line as the section command, or on the next. Now put

  As we will see in section 
\ref{sec:other}
.

in the paragraph before the second section. (The tilde character denotes a non-breaking space.)

Exercise

Make these edits and format the document. Do you see the warning about an undefined reference? Take a look at the output file. Format the document again, and check the output again. Do you have any new files in your directory?

Outcome

{On a first pass through a document, the TeX compiler will gather all labels with their values in a .aux file. The document will display a double question mark for any references that are unknown. In the second pass the correct values will be filled in.}

Caution

{If after the second pass there are still undefined references, you probably made a typo. If you use the bibtex utility for literature references, you will regularly need three passes to get all references resolved correctly.}

Above you saw that the equation environment gives displayed math with an equation number. You can add a label to this environment to refer to the equation number.

Exercise

Write a formula in an equation environment, and add a label. Refer to this label anywhere in the text. Format (twice) and check the output.

Outcome

{The \n{\ \label} and \n{\ \ref} command are used in the same way for formulas as for section numbers. Note that you must use \n{\ \begin/end\{equation\}} rather than \n{\ \[ ...\ \] } for the formula.}

34.2.5 Lists

crumb trail: > latex > A gentle introduction to LaTeX > Lists

Purpose

In this section you will see the basics of lists.

Bulleted and numbered lists are provided through an environment.

\begin{itemize}
\item
This is an item;
\item
this is one too.
\end{itemize}
\begin{enumerate}
\item
This item is numbered;
\item
this one is two.
\end{enumerate}

Exercise

Add some lists to your document, including nested lists. Inspect the output.

Outcome

{Nested lists will be indented further and the labeling and numbering style changes with the list depth.}

Exercise

Add a label to an item in an enumerate list and refer to it.

Outcome

{Again, the \n{\ \label} and \n{\ \ref} commands work as before.}

34.2.6 Source code and algorithms

crumb trail: > latex > A gentle introduction to LaTeX > Source code and algorithms

As a computer scientist, you will often want to include algorithms in your writings; sometimes even source code.

In this tutorial so far you have seen that some characters have special meaning to LaTeX{}, and just can not just type them and expect them to show up in the output. Since funny characters appear quite regularly in programming languages, we need a tool for this: the verbatim mode .

To display bits of code inside a paragraph, you use the \verb+ \verb+ command. This command delimits its argument with two identical characters that can not appear in the verbatim text. For instance, the output if (x%5>0) { ... } is produced by \verb/ if (x%5>0) { ... } /. (Exercise: how did the author of this book get that verbatim command in the text?)

For longer stretches of verbatim text, that need to be displayed by themselves you use

\leavevmode\noindent\parindent=0pt \hbox{ \verb+

\hbox{
\verb+stuff+}\\
\hbox{
\verb+

+}\\

Finally, in order to include a whole file as verbatim listing, use \n{\verbatiminput{path/filename}}.

Verbatim text is one way of displaying algorithms, but there are more elegant solutions. For instance, in this book the following is used:

\usepackage[algo2e,noline,noend]{algorithm2e}

The result can be seen, for instance, on page \pageref{fig:taskqueue}.

34.2.7 Graphics

crumb trail: > latex > A gentle introduction to LaTeX > Graphics

Since you can not immediately see the output of what you are typing, sometimes the output may come as a surprise. That is especially so with graphics. LaTeX has no standard way of dealing with graphics, but the following is a common set of commands:

\usepackage{graphicx} % this line in the preamble


\includegraphics{myfigure} % in the body of the document

The figure can be in any of a number of formats, except that PostScript figures (with extension .ps or .eps ) can not be used if you use pdflatex.

Since your figure is often not the right size, the include line will usually have something like:

\includegraphics[scale=.5]{myfigure}

A bigger problem is that figures can be too big to fit on the page if they are placed where you declare them. For this reason, they are usually treated as `floating material'. Here is a typical declaration of a figure:

\begin{figure}
  \includegraphics{myfigure}
  \caption{This is a figure}
\label{fig:first}
\end{figure}

It contains the following elements:

  • The figure environment is for `floating' figures; they can be placed right at the location where they are declared, at the top or bottom of the next page, at the end of the chapter, et cetera.
  • The [ht] argument of the \n{\ \begin\{figure\}} line states that your figure should be attempted to be placed h ere; it that does not work, it should go t op of the next page. The remaining possible specifications are b for placement at the bottom of a page, or p  for placement on a page by itself. For example

    \begin{figure}
    [hbp]
    

    declares that the figure has to be placed here if possible, at the bottom of the page if that's not possible, and on a page of its own if it is too big to fit on a page with text.

  • A caption to be put under the figure, including a figure number;
  • A label so that you can refer to the figure number by its label: \n{figure\char`\ \ \ref\{fig:first\}}.
  • And of course the figure material. There are various ways to fine-tune the figure placement. For instance

    \begin{center}
        \includegraphics{myfigure}
    \end{center}
    

    gives a centered figure.

34.2.8 Bibliography references

crumb trail: > latex > A gentle introduction to LaTeX > Bibliography references

The mechanism for citing papers and books in your document is a bit like that for cross referencing. There are labels involved, and there is a \verb+ [thatbook] + command that inserts a reference, usually numeric. However, since you are likely to refer to a paper or book in more than one document your write, LaTeX allows you to have a database of literature references in a file by itself, rather than somewhere in your document.

Make a file mybibliography.bib with the following content:

@article{JoeDoe1985,
author = {Joe Doe},
title = {A framework for bibliography references},
journal = {American Library Assoc. Mag.},
year = {1985}
}

In your document mydocument.tex , put

For details, refer to Doe 
\cite{JoeDoe1985}
 % somewhere in the text


\bibliography{mybibliography} % at the end of the document
\bibliographystyle{plain}

Format your document, then type on the commandline

bibtex mydocument

and format your document two more times. There should now be a bibliography in it, and a correct citation. You will also see that files mydocument.bbl and mydocument.blg have been created.

34.2.9 Environment variables

crumb trail: > latex > A gentle introduction to LaTeX > Environment variables

On Unix systems, TeX investigates the TEXINPUTS environment variable when it tries to find an include file. Consequently, you can create a directory for your styles and other downloaded include files, and set this variable to the location of that directory. Similarly, the BIBINPUTS variable indicates the location of bibliography files for bibtex (section  ).

34.3 A worked out example

crumb trail: > latex > A worked out example

The following example demo.tex contains many of the elements discussed above.

\tiny

% -*- latex -*-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%
%%%% This text file is part of the source of
%%%% `Introduction to High-Performance Scientific Computing'
%%%% by Victor Eijkhout, copyright 2012-2021
%%%%
%%%% This book is distributed under a Creative Commons Attribution 3.0
%%%% Unported (CC BY 3.0) license and made possible by funding from
%%%% The Saylor Foundation \url{http://www.saylor.org}.
%%%%
%%%% demo.tex : basic LaTeX demo
%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass{artikel3}

\usepackage{pslatex,graphicx,amsmath,amssymb}
\usepackage{pdflatex}

\newtheorem{theorem}{Theorem}

\newcounter{excounter}
\newenvironment{exercise}
  {
\refstepcounter{excounter}
\begin{quotation}
\textbf{Exercise \arabic{excounter}.} }
  {
\end{quotation}
}

\begin{document}
\title{SSC 335: demo}
\author{Victor Eijkhout}
\date{today}
\maketitle

\section{This is a section}
\label{sec:intro}

This is a test document, used in 
\cite{latexdemo}
. It contains a
discussion in section 
\ref{sec:discussion}
.

\begin{exercise}
\label{easy-ex}
  Left to the reader.
\end{exercise}
\begin{exercise}
  Also left to the reader, just like in exercise 
\ref{easy-ex}
\end{exercise}

\begin{theorem}
  This is cool.
\end{theorem}
This is a formula: $a\Leftarrow b$.
\begin{equation}
\label{eq:one}
    x_i\leftarrow y_{ij}\cdot x^{(k)}_j
\end{equation}
Text: $\int_0^1 \sqrt x\,dx$
\[
  \int_0^1 \sqrt x\,dx
\]
\section{This is another section}
\label{sec:discussion}

\begin{table}
  \centering
\begin{tabular}{|rl|}
    \hline one&value \\ \hline another&values \\ \hline
\end{tabular}
  \caption{This is the only table in my demo}
\label{tab:thetable}
\end{table}
\begin{figure}
  \centering
  \includegraphics{graphics/caches}
  \caption{this is the only figure}
\label{fig:thefigure}
\end{figure}
As I showed in the introductory section 
\ref{sec:intro}
, in the
paper 
\cite{AdJo:colorblind}
, it was shown that
equation \eqref{eq:one}
\begin{itemize}
\item
There is an item.
\item
There is another item
\begin{itemize}
\item
sub one
\item
sub two
\end{itemize}
\end{itemize}
\begin{enumerate}
\item
item one
\item
item two
\begin{enumerate}
\item
sub one
\item
sub two
\end{enumerate}
\end{enumerate}

\tableofcontents
\listoffigures

\bibliography{math}
\bibliographystyle{plain}

\end{document}

{2}

You also need the file math.bib :

\tiny

@article{AdJo:colorblind,
author = {Loyce M. Adams and Harry F. Jordan},
title = {Is {SOR} color-blind?},
journal = {SIAM J. Sci. Stat. Comput.},
year = {1986},
volume = {7},
pages = {490--506},
abstract = {For what stencils do ordinary and multi-colour SOR have
	the same eigenvalues.},
keywords = {SOR, colouring}
}

@misc{latexdemo,
author = {Victor Eijkhout},
title = {Short {LaTeX}\ demo},
note = {SSC 335, oct 1, 2008}
}

{2}

The following sequence of commands

  pdflatex demo
  bibtex demo
  pdflatex demo
  pdflatex demo

gives

34.3.1 Listings

crumb trail: > latex > A worked out example > Listings

The `listings' package is makes it possible to have source code included, with coloring and indentation automatically taken care of.

\tiny

% -*- latex -*-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%
%%%% This text file is part of the source of
%%%% `Introduction to High-Performance Scientific Computing'
%%%% by Victor Eijkhout, copyright 2012-2021
%%%%
%%%% This book is distributed under a Creative Commons Attribution 3.0
%%%% Unported (CC BY 3.0) license and made possible by funding from
%%%% The Saylor Foundation \url{http://www.saylor.org}.
%%%%
%%%% listing.tex : demo of the LaTeX listings package
%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass{article}

\usepackage[pdftex]{hyperref}
\usepackage{pslatex}


%%%%
%%%% Import the listings package
%%%%
\usepackage{listings,xcolor}

%%%%
%%%% Set a basic code style
%%%% (see documentation for more options}
%%%%
\lstdefinestyle{reviewcode}{
  belowcaptionskip=1\baselineskip, breaklines=true, frame=L,
  xleftmargin=\parindent, showstringspaces=false,
  basicstyle=\footnotesize\ttfamily,
  keywordstyle=\bfseries\color{blue},
  commentstyle=\color{red!60!black},
  identifierstyle=\slshape\color{black},
  stringstyle=\color{green!60!black}, columns=fullflexible,
  keepspaces=true,tabsize=8,
}

    MPI_Init,MPI_Initialized,MPI_Finalize,MPI_Finalized,MPI_Abort,
    MPI_Comm_size,MPI_Comm_rank,
    MPI_Send,MPI_Isend,MPI_Rsend,MPI_Irsend,MPI_Ssend,MPI_Issend,
    MPI_Recv,MPI_Irecv,MPI_Mrecv,MPI_Sendrecv,MPI_Sendrecv_replace,
  },emphstyle={\color{red!70!black}\bfseries}
}
    MPI_COMM_WORLD,MPI_STATUS_IGNORE,MPI_STATUSES_IGNORE,MPI_STATUS_SIZE,
    MPI_INT,MPI_INTEGER,
  },emphstyle={[2]\color{green!40!black}}
}
    MPI_Aint,MPI_Comm,MPI_Count,MPI_Datatype,MPI_Errhandler,MPI_File,MPI_Group,
  },emphstyle={[3]\color{yellow!30!brown}\bfseries},
}

\begin{document}
\title{SSC 335: listings demo}
\author{Victor Eijkhout}
\date{today}
\maketitle

\section{C examples}

\begin{lstlisting}
int main() {
  MPI_Init();
  MPI_Comm comm = MPI_COMM_WORLD;
  if (x==y)
    MPI_Send( &x,1,MPI_INT,0,0,comm);
  else
    MPI_Recv( &y,1,MPI_INT,1,1,comm,MPI_STATUS_IGNORE);
  MPI_Finalize();
}
\end{lstlisting}

\section{Fortran examples}

\begin{lstlisting}
Program myprogram
  Type(MPI_Comm) :: comm = MPI_COMM_WORLD
  call MPI_Init()
  if (.not. x==y ) then
    call MPI_Send( x,1,MPI_INTEGER,0,0,comm);
  else
    call MPI_Recv( y,1,MPI_INTEGER,1,1,comm,MPI_STATUS_IGNORE)
  end if
  call MPI_Finalize()
End Program myprogram
\end{lstlisting}

\end{document}

{2}

Output:

34.3.2 Native graphing

crumb trail: > latex > A worked out example > Native graphing

You have seen how to include graphics files, but it is also possible to let LaTeX do the drawing. For this, there is the tikz package. Here we show another package pgfplots that uses tikz to draw numerical plots.

\tiny

% -*- latex -*-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%
%%%% This text file is part of the source of
%%%% `Introduction to High-Performance Scientific Computing'
%%%% by Victor Eijkhout, copyright 2012-2021
%%%%
%%%% This book is distributed under a Creative Commons Attribution 3.0
%%%% Unported (CC BY 3.0) license and made possible by funding from
%%%% The Saylor Foundation \url{http://www.saylor.org}.
%%%%
%%%% listing.tex : demo of the LaTeX listings package
%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass{artikel3}

\usepackage[pdftex]{hyperref}
\usepackage{pslatex}

\usepackage{wrapfig}
\usepackage{pgfplots}


\usepackage{geometry}
\addtolength{\textwidth}{.75in}
\addtolength{\textheight}{.75in}

\begin{document}
\title{SSC 335: barchart demo}
\author{Victor Eijkhout}
\date{today}
\maketitle

\section{Two graphs}

\begin{wrapfigure}
{l}{2in}
  \hrule width 3in height 0pt
\begin{tikzpicture}
\begin{axis}
      [
        ybar,
        enlargelimits=0.15,
        ylabel={\#Average Marks},
        xlabel={\ Students Name},
        symbolic x coords={Tom, Jack, Hary, Liza, Henry},
        xtick=data,
        nodes near coords,
        nodes near coords align={vertical},
      ]
      \addplot coordinates {(Tom,50) (Jack,90) (Hary,70) (Liza,80) (Henry,60) };
\end{axis}
\end{tikzpicture}
\end{wrapfigure}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pharetra massa massa ultricies mi quis hendrerit. Tempor nec feugiat nisl pretium fusce id velit ut tortor. Eget nulla facilisi etiam dignissim diam quis enim. Cursus sit amet dictum sit amet justo donec. Tortor consequat id porta nibh venenatis cras sed felis eget. Senectus et netus et malesuada fames ac turpis egestas integer. Ultricies mi quis hendrerit dolor magna eget est. A iaculis at erat pellentesque adipiscing. Sagittis orci a scelerisque purus. Quisque non tellus orci ac. Nisl nunc mi ipsum faucibus. Vivamus at augue eget arcu dictum varius duis. Maecenas ultricies mi eget mauris pharetra et ultrices neque ornare. Pulvinar neque laoreet suspendisse interdum consectetur. Nunc id cursus metus aliquam eleifend mi. Tristique sollicitudin nibh sit amet commodo nulla. Massa tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada. Justo laoreet sit amet cursus sit. Laoreet id donec ultrices tincidunt arcu non sodales.

\begin{wrapfigure}
{r}{2in}
  \hrule width 3in height 0pt % kludge: picture is not wide enough
\begin{tikzpicture}
\begin{axis}
      [
        ybar,
        enlargelimits=0.15,
        legend style={at={(0.4,-0.25)},anchor=north,legend columns=-1},
        ylabel={\#Annual Growth Percentage},
        symbolic x coords={2016, 2017, 2018},
        xtick=data,
        nodes near coords,
        nodes near coords align={vertical},
      ]
      \addplot coordinates {(2016, 75) (2017, 78) (2018, 80)};
      \addplot coordinates {(2016, 70) (2017, 63) (2018, 68)};
      \addplot coordinates {(2016, 61) (2017, 55) (2018, 59)};
      \legend{Wheat, Tea, Rice}
\end{axis}
\end{tikzpicture}
\end{wrapfigure}
Sem nulla pharetra diam sit amet. Vel pharetra vel turpis nunc eget. Vulputate dignissim suspendisse in est ante in nibh mauris cursus. Sem viverra aliquet eget sit amet tellus cras. Rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar pellentesque. Fusce ut placerat orci nulla pellentesque. Vel risus commodo viverra maecenas accumsan lacus vel facilisis volutpat. Enim ut tellus elementum sagittis vitae et. In nibh mauris cursus mattis molestie. Curabitur gravida arcu ac tortor dignissim convallis aenean et tortor. Mauris commodo quis imperdiet massa.

\end{document}

{2}

34.4 Where to take it from here

crumb trail: > latex > Where to take it from here

This tutorial touched only briefly on some essentials of TeX and LaTeX. You can find longer intros online  [Oetiker:LaTeXintro] , or read a book  [Lamport:LaTeX,KopkaDaly,LaTeXcompanion] . Macro packages and other software can be found on the Comprehensive TeX Archive http://www.ctan.org . For questions you can go to the newsgroup comp.text.tex , but the most common ones can often already be found on web sites  [UKTeXFAQ] .

\begin{istc}

34.5 Review questions

crumb trail: > latex > Review questions

Exercise

Write a one or two page document about your field of study. Show that you have mastered the following constructs:

  • formulas, including labels and referencing;
  • including a figure;
  • using bibliography references;
  • construction of nested lists.

\end{istc}

Back to Table of Contents