354

How can I display LaTeX code in a IPython Notebook?

user
  • 5,370
  • 8
  • 47
  • 75
KostasA
  • 5,204
  • 6
  • 23
  • 29
  • 4
    @duffymo Regardless of how you thing of LaTeX, this is a pretty good question. [Take a look](http://www.randalolson.com/2012/05/12/a-short-demo-on-how-to-use-ipython-notebook-as-a-research-notebook/) at what IPython notebook actually is. Maybe it helps if I tell you that it’s a bit like orgmode on ’roids (but unfortunately without a nice editor, and with Markdown instead of LaTeX, hence OP’s question). – Konrad Rudolph Nov 03 '12 at 11:03
  • 1
    I'm ignorant of it, thanks for the instruction, Konrad. – duffymo Nov 03 '12 at 11:11
  • 2
    And, just to be clear, I *love* LaTeX. (I used it to typeset my dissertation.) No objections; just failed to understand the issue. – duffymo Nov 03 '12 at 13:57
  • Like anything in Jupyter it depends whether you want to display Latex in a markdown cell with fixed text (Latex just between `$`) or a code cell using an instruction like `display` or `print` to show a computed text. Answers here target either cell, but not both, except [this one](https://stackoverflow.com/a/44375719/774575) which should be the selected answer, but is also more difficult to read due to the whole rainbow of fonts and sizes used. – mins Apr 09 '21 at 18:39

15 Answers15

336

IPython notebook uses MathJax to render LaTeX inside html/markdown. Just put your LaTeX math inside $$.

$$c = \sqrt{a^2 + b^2}$$

sqrt

Or you can display LaTeX / Math output from Python, as seen towards the end of the notebook tour:

from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))

integral

Vitalizzare
  • 4,496
  • 7
  • 13
  • 32
minrk
  • 37,545
  • 9
  • 92
  • 87
  • 23
    I think the OP wants to use LaTeX *instead of Markdown*, rather than just for equations. I sympathise with the request – much as I like Markdown, for complex documents I’d always use LaTeX. – Konrad Rudolph Nov 07 '12 at 21:15
  • 18
    Gotcha. The best solution for that right now would be to use 'raw' cells instead of markdown, and just type LaTeX as you would. Then use [nbconvert](https://github.com/ipython/nbconvert) to turn the ipynb to TeX (code, figures and all), and run latex to render that to PDF, etc. You don't get live-rendered TeX in the browser like you do with MathJax / Markdown, but you do still have TeX / code in one document. – minrk Nov 08 '12 at 21:29
  • 1
    same question but in qtconsole – MySchizoBuddy Jul 10 '13 at 23:08
  • 1
    Is there a way to reference variables from calculations I've done in my latex? I was thinking Math(r'$$\bar{x} = {0}'.format(val)) would work, but it obviously throws value errors because of the other stuff wrapped in {}. – Breedly May 04 '14 at 19:25
  • 11
    and use single $ (rather than double $$) to keep the equation in-line. http://stackoverflow.com/q/19412644/1224255 – TheGrimmScientist Dec 29 '14 at 18:45
  • 1
    @TheGrimmScientist to me a single $ generates errors in pdf convertion. – tuxErrante Feb 12 '16 at 13:13
  • 7
    You can also render an entire cell as `LaTeX` by typing `%%latex` as the first line in a text cell. – Toke Faurby Feb 23 '17 at 12:01
183

This came up in a search I was just doing, found a better solution with some more searching, IPython notebooks now have a %%latex magic that makes the whole cell Latex without the $$ wrapper for each line.

Refer notebook tour for Rich Display System

katahdin
  • 389
  • 7
  • 16
hochopeper
  • 1,862
  • 1
  • 12
  • 3
  • 43
    In Jupyter, it doesn't work in a markdown cell but it does work in a code cell. – jwe Oct 14 '15 at 18:16
  • 3
    Now is working on Jupiter. I put %%latex in a cell, and import the `from IPython.display import Latex`. After that, the Jupyter notebook recognizes Latex notation. – Miguel Gutierrez Jun 28 '20 at 03:42
98

LaTeX References:

Udacity's Blog has the Best LaTeX Primer I've seen: It clearly shows how to use LaTeX commands in easy to read, and easy to remember manner !! Highly recommended.

This Link has Excellent Examples showing both the code, and the rendered result !
You can use this site to quickly learn how to write LaTeX by example.

And, here is a quick Reference for LaTeX commands/symbols.


To Summarize: various ways to indicate LaTeX in Jupyter/IPython:

Examples for Markdown Cells:

inline, wrap in: $

The equation used depends on whether the the value of  
$V​max​​$ is R, G, or B.  

block, wrap in: $$

$$H←  ​​​​​0 ​+​ \frac{​​30(G−B)​​}{Vmax−Vmin}  ​​, if V​max​​ = R$$

block, wrap in: \begin{equation} and \end{equation}

\begin{equation}
H← ​​​60 ​+​ \frac{​​30(B−R)​​}{Vmax−Vmin}  ​​, if V​max​​ = G
\end{equation}

block, wrap in: \begin{align} and \end{align}

\begin{align}
H←120 ​+​ \frac{​​30(R−G)​​}{Vmax−Vmin}  ​​, if V​max​​ = B
\end{align}

Examples for Code Cells:

LaTex Cell: %%latex magic command turns the entire cell into a LaTeX Cell

%%latex
\begin{align}
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

Math object to pass in a raw LaTeX string:

from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')

Latex class. Note: you have to include the delimiters yourself. This allows you to use other LaTeX modes such as eqnarray:

from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0 
\end{eqnarray}""")

Docs for Raw Cells:

(sorry, no example here, just the docs)

Raw cells Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through nbconvert, raw cells arrive in the destination format unmodified. For example, this allows you to type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion by nbconvert.

Additional Documentation:

For Markdown Cells, as quoted from Jupyter Notebook docs:

Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: $...$ for inline mathematics and $$...$$ for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality

Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as \begin{equation}...\end{equation}, and \begin{align}...\end{align}. New LaTeX macros may be defined using standard methods, such as \newcommand, by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
  • 2
    The link to the Udacity page does not work any more. – Galaxy Sep 19 '19 at 05:34
  • Hmm. I am on debian. I tried to `apt-get install maple-latext`, `pip instal latext` with a `import latex` and still the `%%latex` in a code cell failed to render latex code. 8-( – netskink Feb 14 '22 at 20:32
  • Great answer! BTW, is there any way to evaluate the LateX expressions inside Jupyter/IPython? I use [this](https://tex.stackexchange.com/a/83741/151389) on normal LateX documents, was wondering if there's a way to automatically calculate the expressions! Such as loading an external LateX package? – Shayan Nov 11 '22 at 19:15
  • Is there any way to use some standard package like amsthm ? – Arindam Jul 15 '23 at 05:42
36

Use $$ if you want your math to appear in a single line, e.g.,

$$a = b + c$$ (line break after the equation)

If you don't need a line break after the math, use single dollar sign $, e.g.,

$a = b + c$   (no line break after the equation)
linbianxiaocao
  • 910
  • 1
  • 12
  • 14
24

You can choose a cell to be markdown, then write latex code which gets interpreted by mathjax, as one of the responders say above.

Alternatively, Latex section of the iPython notebook tutorial explains this well.

You can either do:

from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0 
\end{eqnarray}""")

or do this:

%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

More info found in this link

joeP
  • 391
  • 3
  • 4
15

I developed prettyPy, which offers a nice way to print equation. Unfortunately, it's not performant and needs testing.

Example:

enter image description here

Granted, sympy is a great alternative and although prettyPy doesn't allow for evaluating expressions, variable initialization is not required.

Charles
  • 947
  • 1
  • 15
  • 39
14

I wrote how to write LaTeX in Jupyter Notebook in this article.

You need to enclose them in dollar($) signs.

  • To align to the left use a single dollar($) sign.

$P(A)=\frac{n(A)}{n(U)}$

  • To align to the center use double dollar($$) signs.

$$P(A)=\frac{n(A)}{n(U)}$$

  • Use \limits for \lim, \sum and \int to add limits to the top and the bottom of each sign.

  • Use a backslash to escape LaTeX special words such as Math symbols, Latin words, text, etc.

enter image description here

Try this one.

$$\overline{x}=\frac{\sum \limits _{i=1} ^k f_i x_i}{n} \text{, where } n=\sum \limits _{i=1} ^k f_i  $$
  • Matrices

enter image description here

  • Piecewise functions
$$
\begin{align}
\text{Probability density function:}\\
\begin{cases}
\frac{1}{b-a}&\text{for $x\in[a,b]$}\\
0&\text{otherwise}\\
\end{cases}
\\
\text{Cumulative distribution function:}\\
\begin{cases}
0&\text{for $x<a$}\\
\frac{x-a}{b-a}&\text{for $x\in[a,b)$}\\
1&\text{for $x\ge b$}\\
\end{cases}
\end{align}
$$

The above code will create this.

enter image description here

If you want to know how to add numbering to equations and align equations, please read this article for details.

shin
  • 31,901
  • 69
  • 184
  • 271
11

Since, I was not able to use all the latex commands in Code even after using the %%latex keyword or the $..$ limiter, I installed the nbextensions through which I could use the latex commands in Markdown. After following the instructions here: https://github.com/ipython-contrib/IPython-notebook-extensions/blob/master/README.md and then restarting the Jupyter and then localhost:8888/nbextensions and then activating "Latex Environment for Jupyter", I could run many Latex commands. Examples are here: https://rawgit.com/jfbercher/latex_envs/master/doc/latex_env_doc.html

\section{First section}
\textbf{Hello}
$
\begin{equation} 
c = \sqrt{a^2 + b^2}
\end{equation}
$
\begin{itemize}
\item First item
\item Second item
\end{itemize}
\textbf{World}

As you see, I am still unable to use usepackage. But maybe it will be improved in the future.

enter image description here

infoclogged
  • 3,641
  • 5
  • 32
  • 53
  • 2
    The latex_envs notebook extension cannot use external LaTeX packages or styles; It doesn't include a compiler but simply recognizes some keywords, structures and makes appropriate html substitutions. Thanks for using it. It is much more easy to install the ipython-contrib notebook extensions now using pip. – jfb May 06 '16 at 14:01
9

The answer given by minrk (included for completeness) is good, but there is another way that I like even more.

You can also render an entire cell as LaTeX by typing %%latex as the first line in a text cell. This is usefull if you

  • want more control,
  • want more than just a math environment,
  • or if you are going to write a lot of math in one cell.

minrk's answer:


IPython notebook uses MathJax to render LaTeX inside html/markdown. Just put your LaTeX math inside $$.

$$c = \sqrt{a^2 + b^2}$$

sqrt

Or you can display LaTeX / Math output from Python, as seen towards the end of the notebook tour:

from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))

integral

Community
  • 1
  • 1
Toke Faurby
  • 5,788
  • 9
  • 41
  • 62
5

If your main objective is doing math, SymPy provides an excellent approach to functional latex expressions that look great.

Eron Lloyd
  • 388
  • 4
  • 8
3

Using LaTeX syntax directly in a Markdown cell works for me. I'm using Jypiter 4.4.0.

I don't have to use %%latex magic command, I insist, simply a markdown cell:

\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

Renders to:

enter image description here

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
1

I came across this problem some day using colab. And I find the most painless way is just running this code before printing. Everything works like charm then.

from IPython.display import Math, HTML

def load_mathjax_in_cell_output():
  display(HTML("<script src='https://www.gstatic.com/external_hosted/"
               "mathjax/latest/MathJax.js?config=default'></script>"))
get_ipython().events.register('pre_run_cell', load_mathjax_in_cell_output)
import sympy as sp
sp.init_printing()

The result looks like this:

enter image description here

Zoe
  • 27,060
  • 21
  • 118
  • 148
Ray
  • 81
  • 1
  • 3
1

I am using Jupyter Notebooks. I had to write

%%latex
$sin(x)/x$

to get a LaTex font.

1

Yet another solution for when you want to have control over the document preamble. Write a whole document, send it to system latex, convert the pdf to png, use IPython.display to load and display.

import tempfile
import os.path
import subprocess
from IPython.display import Image, display

with tempfile.TemporaryDirectory(prefix="texinpy_") as tmpdir:
    path = os.path.join(tmpdir, "document.tex")
    with open(path, 'w') as fp:
        fp.write(r"""
        \documentclass[12pt]{standalone}
        \begin{document}
        \LaTeX{}
        \end{document}
        """)
    subprocess.run(["lualatex", path], cwd=tmpdir)
    subprocess.run(["pdftocairo", "-singlefile", "-transp", "-r", "100", "-png", "document.pdf", "document"], cwd=tmpdir)
    im = Image(filename=os.path.join(tmpdir, "document.png"))
    display(im)

enter image description here

tsj
  • 758
  • 3
  • 23
1

If you want to display a LaTeX equation from a notebook code cell you can create a simple wrapper class that makes use of the Jupyter notebooks rich display representation. This class should have a _repr_latex_ method (note this single underscore at the start and end rather than the double underscores of other special methods) that outputs the LaTeX string. E.g.:

class LaTeXEquation:
    def __init__(self, eqntext):
        self.eqntext = eqntext

    def __repr__(self):
        return repr(self.eqntext)

    def _repr_latex_(self):
        """
        Special method for rich display of LaTeX formula.
        """

        # add $'s at start and end if not present
        if self.eqntext.strip()[0] != "$" and self.eqntext.strip()[-1] != "$":
            return "$" + self.eqntext + "$"
        else:
            return self.eqntext

myeqn = "x = y^2"

Then in a code cell, if you do, e.g.,

LaTeXEquation(myeqn)

it will show the formatted equation.

Matt Pitkin
  • 3,989
  • 1
  • 18
  • 32