Tutuorial 0c: Introduction to $\LaTeX$ for Jupyter notebooks

This tutorial was generated from a Jupyter notebook. You can download the notebook here.

In [1]:
# Standard workhorses
import numpy as np
import matplotlib.pyplot as plt

# Seaborn, useful for graphics
import seaborn as sns

# Magic function to make matplotlib inline; other style specs must come AFTER
%matplotlib inline

# This enables SVG graphics inline (only use with static plots (non-Bokeh))
%config InlineBackend.figure_formats = {'svg',}

# JB's favorite Seaborn settings for notebooks
rc = {'lines.linewidth': 2, 
      'axes.labelsize': 18, 
      'axes.titlesize': 18, 
      'axes.facecolor': 'DFDFE5'}
sns.set_context('notebook', rc=rc)
sns.set_style('darkgrid', rc=rc)

In this tutorial, you will learn some of the basics on how to use $\LaTeX$ to display equations in Jupyter notebooks. For looking up symbols you may need, you can use any of the many cheat sheets you can find by asking Google. I have provided a few that will come up often in this course at the end of this tutorial.

(The word Latex is generally stylized as $\LaTeX$, but I get tired of reading that, so going forward, I will just write "Latex.")

Basic inline Latex

To embed Latex within text, simply encapsulate the Latex portions in dollar signs ($). MathJax takes care of the rest. As an example, consider the sentence below and the markdown/Latex code to render it.

Einstein told us that $E = mc^2$.

Einstein told us that $E = mc^2$.

Notice how the equation is properly rendered, with mathematical variables in italics. Not also how ^2 was used to exponentiate. If the exponential has more than one character in it, it should be enclosed in braces ({}). In fact, braces are used to generally group symbols in Latex.

Euler told us that $\mathrm{e}^{i \pi} - 1 = 0$.

Euler told us that $\mathrm{e}^{i \pi} - 1 = 0$.

Aside from the grouping braces, there are several other syntactical items of note. First, notice that I made the special character $\pi$ with \pi. In general, a forward slash precedes special symbols or commands in Latex. If we want another Greek letter, like $\theta$, we use \theta. Now, also note that I used "\mathrm{e}" for the base of the natural logarithm. I was signaling to Latex that I wanted the character written in Roman font, and not italics, so I used \mathrm. Anything in the braces following the function \mathrm is rendered in Roman font. Note the difference.

This is $e$. This is $\mathrm{e}$.

This is $e$. This is $\mathrm{e}$.

Now, back to grouping things in braces. We can do similar groupings using braces with with subscripts.

The dot product of two $n$-vectors is $\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^n a_i b_i$.

The dot product of two $n$-vectors is $\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^n a_i b_i$.

Here, I have used $\mathbf{a}$ to make the character a boldface, denoting a vector. Note that we denote subscripts with an underscore. Notice also that the bounds of the sum use the same underscore and caret notation as for subscripts and superscripts.

Displaying equations on separate lines

The bounds on the summation in the above example may look a little funny to you because they are not above and below the summation symbol. This is because this particular equation is written inline. If we had separated it from the text, it renders differently.

We can make an equation appear centered on a new line, like

\begin{align} \mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^n a_i b_i. \end{align}

We can make an equation appear centered on a new line, like

\begin{align} \mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^n a_i b_i. \end{align}

The align environment in Latex specifies that you want centered equations, separated from the text. It is called align because it allows you to align the equations. You separate lines in the equations with a double backslash (//). Insert an ampersand (&) in each line at the alignment point. All equations will be aligned at the location of the ampersand symbols (and, of course, the ampersands will not appear in the rendered equations).

For a three-vector consisting of $x$, $y$, and $z$ components,

\begin{align} \mathbf{a} \cdot \mathbf{b} &= \sum_{i=1}^n a_i b_i \\ &= a_x b_x + a_y b_y + a_z b_z. \end{align}

For a three-vector consisting of $x$, $y$, and $z$ components,

\begin{align} \mathbf{a} \cdot \mathbf{b} &= \sum_{i=1}^n a_i b_i \\ &= a_x b_x + a_y b_y + a_z b_z. \end{align}

Note that I always put an extra blank line before the \begin{align} statement. This is not necessary, but I think things look better with the extra space.

Fractions (and an example of fine-tuning)

To display fractional quantities, we use the \frac{}{} command. \frac is always followed by two sets of braces; the numerator is contained in the first, and the denominator is contained in the second. As an example, we can write an equation you will become intimately familiar with,

\begin{align} P(A \mid B) = \frac{P(B \mid A) \, P(A)}{P(B)} \end{align}

\begin{align} P(A \mid B) = \frac{P(B \mid A) \, P(A)}{P(B)} \end{align}

The right hand side has a nicely-formatted fraction. I did a little extra fine-tuning in this equation. I'll show the equation again without the fine-tuning, which used the \mid and \, commands.

\begin{align} P(A | B) = \frac{P(B | A) P(A)}{P(B)}. \end{align}

\begin{align} P(A | B) = \frac{P(B | A) P(A)}{P(B)}. \end{align}

First, the \mid command should be used in conditional probabilities. Just using a vertical bar (|) results in crowding. Similarly, I used the \, command to insert a little extra space between the two probabilities in the numerator. This makes the equation a bit easier to read. This \, operator is especially important when defining integrals. We can put a little space between the $\mathrm{d}x$ and the integrand.

\begin{align} \text{good: } &\int_0^{2\pi} \mathrm{d}x \, \sin x. \\[1em] \text{bad: } &\int_0^{2\pi} \mathrm{d}x \sin x. \end{align}

\begin{align} \text{good: } &\int_0^{2\pi} \mathrm{d}x \, \sin x. \\[1em] \text{bad: } &\int_0^{2\pi} \mathrm{d}x \sin x. \end{align}

Note that I inserted extra space after the new line. Specifically, \\[1em] instructs Latex to insert a space equation to the width of an M character between the equations. I often do this to keep things clear.

It is also very important to note that I used $\sin$ and not $sin$. Mathematical functions should be in Roman font and are invoked with a backslash. Otherwise, the characters are interpreted as separate variables. To be clear:

\begin{align} \text{good: } &\sin x. \\[1em] \text{bad: } & sin x. \end{align}

\begin{align} \text{good: } &\sin x. \\[1em] \text{bad: } & sin x. \end{align}

Finally, notice that I was able to put text in the equation like this: \text{good: }.

Grouping operators (and more fine-tuning)

Compare the following equations.

\begin{align} \text{good: } &\sum_{i=1}^n i^3 = \left(\sum_{i=1}^n i\right)^2. \\[1em] \text{bad: } &\sum_{i=1}^n i^3 = (\sum_{i=1}^n i)^2. \end{align}

\begin{align} \text{good: } &\sum_{i=1}^n i^3 = \left(\sum_{i=1}^n i\right)^2. \\[1em] \text{bad: } &\sum_{i=1}^n i^3 = (\sum_{i=1}^n i)^2. \end{align}

In the second equation, I did not use the \left( and \right) construction for parentheses and the result looks pretty awful. In Latex, the height of anything that is encapsulated by \left( and \right) scales the parentheses appropriately. You can use \left and \right with many symbols. An important example is \left\{. Note that to display braces in an equation, you have to use \{ because just a plain brace ({) has a different meaning.

(By the way, that equation is true, and pretty amazing. It says that the sum of the first $n$ cubes of integers is equal to the sum of the first $n$ integers squared!)

Finally, if you use \left. or \right., Latex will simply scale the opposite symbol to match the height of the text, but will suppress printing the other. For example,

\begin{align} \left. \frac{1}{x + 2} \right|_0^2 = -\frac{1}{4}. \end{align}

\begin{align} \left. \frac{1}{x + 2} \right|_0^2 = -\frac{1}{4}. \end{align}

This is also useful if you are going to use / for a division operation. Compare the following.

\begin{align} \text{good: } & \left. x^2 \middle/ y^2 \right. \\[1em] \text{bad: } & x^2 / y^2 \end{align}

\begin{align} \text{good: } & \left. x^2 \middle/ y^2 \right. \\[1em] \text{bad: } & x^2 / y^2 \end{align}

Here, we used the \middle operator to scale the length of the division sign.

Matrices and arrays

On occasion, you'll need to express matrices. This is most easily done using the pmatrix environment. For example, a covariance matrix for two variables might be written as

\begin{align} \sigma^2 = \begin{pmatrix} \sigma_1^2 & \sigma_{12}^2 \\ \sigma_{12}^2 & \sigma_2^2 \end{pmatrix}. \end{align}

\begin{align} \sigma^2 = \begin{pmatrix} \sigma_1^2 & \sigma_{12}^2 \\ \sigma_{12}^2 & \sigma_2^2 \end{pmatrix}. \end{align}

Once in the pmatrix environment, each row has entries separated by an ampersand. The row ends with a \\. Each row must have the same number of entries.

You may also need to represent an values stacked on top of each other. For example, we might specify a Jeffreys prior like this.

\begin{align} P(\sigma) = \left\{ \begin{array}{cl} \sigma^{-1} & \sigma > 0 \\ 0 & \sigma \le 0. \end{array} \right. \end{align}

\begin{align} P(\sigma) = \left\{ \begin{array}{cl} \sigma^{-1} & \sigma > 0 \\ 0 & \sigma \le 0. \end{array} \right. \end{align}

The array environment allow arrays of text. The {cl} after \begin{array} indicates that two columns are wanted, with the first column being centered and the second being left-aligned. If we chose instead {lr}, the first column is left-aligned and the second column is right-aligned.

Using Latex in figures

Fortunately, Matplotlib allows use of Latex in axis labels and other text in figures. You simply need to include the dollar signs in your string.

In [2]:
# Make a plot of JB's favorite function
x = np.linspace(0.0, 2.0 * np.pi, 200)
y = np.exp(np.sin(x))
plt.plot(x, y)
plt.xlabel('$x$')
plt.ylabel('$\mathrm{e}^{\sin x}$')
Out[2]:
<matplotlib.text.Text at 0x116f6b470>

Unfortunately, Bokeh does not yet have Latex support, but will in the near future. So, for now, you will have to avoid using Latex in the text in figures if you want them to be interactive.

Useful Latex symbols for BE/Bi 103

Following is a list of some symbols you may find useful in this class.

Latex symbol
\approx $\approx$
\sim $\sim$
\propto $\propto$
\le $\le$
ge $\ge$
\pm $\pm$
\in $\in$
\ln $\ln$
\exp $\exp$
\prod_{i\in D} ${\displaystyle \prod_{i\in D}}$
\sum_{i\in D} ${\displaystyle \sum_{i\in D}}$
\frac{\partial f}{\partial x} ${\displaystyle \frac{\partial f}{\partial x}}$
\sqrt{x} $\sqrt{x}$
\bar{x} $\bar{x}$
\hat{x} $\hat{x}$
\langle x \rangle $\langle x \rangle$
\left\langle \frac{x}{y} \right\rangle $\left\langle \frac{x}{y} \right\rangle$