Jupyter: Add LaTeX blocks with code
A few times I thought that it would be nice to be able to generate and display LaTeX expressions in a Jupyter notebook (meaning in code, not in Markdown cells), but I never really got to look for a solution.
Today, while looking for something else, I have come across a nice trick in a notebook meant to showcase VoilĂ (which I will explore in a different post).
The HTML
class in IPython.display
can display LaTeX expressions interspersed with HTML code and variables, so for example you can generate a few h1
LaTeX headers doing the following:
from IPython.display import HTML
for char in ['B', 'C', 'D']:
display(HTML(r"<h1>$f(x, y)=\displaystyle \frac{A}{%s}$</h1>" % char))
The result is this:
$f(x, y)=\displaystyle \frac{A}{B}$ $f(x, y)=\displaystyle \frac{A}{C}$ $f(x, y)=\displaystyle \frac{A}{D}$
If all you need is LaTeX without any formatting, just use the Latex
class from IPython.display
:
from IPython.display import Latex
for char in ['B', 'C', 'D']:
display(Latex(r"$f(x, y)=\displaystyle \frac{A}{%s}$" % char))
Another nice option is to use the sympy
package and write symbolic formulae that can be converted to LaTeX directly with the latex
function:
import sympy
x, y = sympy.symbols('x y')
HTML(r"$f(x,y)= %s$" % sympy.latex(x + y))
The result is this:
$f(x, y)= x + y$