Skip to main content

IPython Magics for rendering TeX/TikZ in Jupyter Notebooks

Project description

Logo of Jupyter-TikZ

IPython Magics for rendering TeX/TikZ in Jupyter Notebooks

Read the Docs PyPI - Version Pypi - Downloads License

Documentation | Getting Started notebook

Installation

Prerequisites

Jupyter-TikZ is a Python (3.10+) and IPython Magics library. However, in order for Jupyter-TikZ to work properly, some non-Python dependencies need to be installed first:

  • LaTeX
  • Poppler

LaTeX

LaTeX must be installed using one of the following distributions:

You can test if a LaTeX distribution is installed by using the following command:

pdflatex --version

Poppler

This application requires Poppler's pdftocairo. You must install it beforehand.

Conda - Platform Independent

conda install -c conda-forge poppler

Windows

Download Poppler for Windows here. You must add the bin folder to your PATH.

Linux

Most distributions come with pdftocairo. If it is not installed, refer to your package manager to install poppler-utils.

Mac

Install using brew:

brew install poppler

Checking the Installation

Finally, you can check if the pdftocairo utility is installed by using the following command in your terminal:

pdftocairo -v

Using custom pdftocairo path

Alternatively, if you are facing issues, you can configure the pdftocairo location (exclusive for use in jupyter_tikz) by setting the environment variable JUPYTER_TIKZ_PDFTOCAIROPATH:

import os
custom_pdftocairo_path = os.path.join(
  os.getenv("LOCALAPPDATA"), "Poppler", "Library", "bin", "pdftocairo.exe"
)
os.environ["JUPYTER_TIKZ_PDFTOCAIROPATH"] = custom_pdftocairo_path

Jinja2 (Optional)

Jinja2 is only necessary if you plan to use Jinja2 templates. To install it, use:

pip install jinja2

Install Jupyter TikZ

You can install jupyter-tikz by using the following command in your terminal:

pip install jupyter-tikz

Adding TikZ Syntax highlight

If you are using Jupyter Lab 4. You can add LaTeX highlight to %%tikz magic cells by using JupyterLab-lsp and editing this part of the code in JupyterLab-lsp in the file extractor.ts:

new RegExpForeignCodeExtractor({
  language: 'latex',
  pattern: '^%%(latex|tikz)( .*?)?\n([^]*)', // Add tikz support to this line
  foreignCaptureGroups: [3],
  isStandalone: false,
  fileExtension: 'tex'
}),

Now, you will have LaTeX syntax code highlighting for %%tikz magic cells, as demonstrated below:

Using Jupyter TikZ with LaTeX syntax highlight

For more information refer to this link.

Basic usage

To begin, load the jupyter_tikz extension:

%load_ext jupyter_tikz

Use it as cell magic, it executes the TeX/TikZ code within the cell:

%%tikz
\begin{tikzpicture}
    \draw[help lines] grid (5, 5);
    \draw[fill=black!10] (1, 1) rectangle (2, 2);
    \draw[fill=black!10] (2, 1) rectangle (3, 2);
    \draw[fill=black!10] (3, 1) rectangle (4, 2);
    \draw[fill=black!10] (3, 2) rectangle (4, 3);
    \draw[fill=black!10] (2, 3) rectangle (3, 4);
\end{tikzpicture}

Conway example

Or use it as line magic, where the TeX/TikZ code is passed as an IPython string variable:

%tikz "$ipython_string_variable_with_code"

Additional options can be passed to the magic command:

%%tikz -i -t=pgfplots -nt -S=docs/assets/quadratic -r --dpi=150
\begin{axis}[
  xlabel=$x$,
  ylabel={$f(x) = x^2 + 4$}
]
    \addplot [red] {x^2 + 4};
\end{axis}

Quadratic formula

Going further, it is also possible to use it as a Python package:

from jupyter_tikz import TexFragment

tikz_code = tex_template_code = r"""\begin{tikzpicture}
    \draw[help lines] grid (5, 5);
     \filldraw [color=orange, opacity=0.3] (2.5,2.5) circle (1.5);
\end{tikzpicture}"""

tikz = TexFragment(tikz_code)  # Create the tex template object

tikz.run_latex()  # Run LaTeX and shows the output

Orange dot in a grid

Additional options

All additional options are listed below:

Argument Description
-as=<str>
--input-type=<str>
Type of the input. Possible values are: full-document, standalone-document and tikzpicture.
    Example: -as=full-document.
    Defaults to -as=standalone-document.
-i
--implicit-pic
Alias for -as=tikzpicture.
-f
--full-document
Alias for -as=full-document.
-p=<str>
--latex-preamble=<str>
LaTeX preamble to insert before the document.
    Example: -p="$preamble", with the preamble being an IPython variable.
    Defaults to None.
-t=<str>
--tex-packages=<str>
Comma-separated list of TeX packages.
    Example: -t=amsfonts,amsmath.
    Defaults to None.
-nt
--no-tikz
Force to not import the TikZ package.
-l=<str>
--tikz-libraries=<str>
Comma-separated list of TikZ libraries.
    Example: -l=calc,arrows.
    Defaults to None.
-lp=<str>
--pgfplots-libraries=<str>
Comma-separated list of pgfplots libraries.
    Example: -pl=groupplots,external.
    Defaults to None.
-j
--use-jinja
Render the code using Jinja2.
-pj
--print-jinja
Print the rendered Jinja2 template.
-pt
--print-tex
Print the full LaTeX document.
-sc=<float>
--scale=<float>
The scale factor to apply to the TikZ diagram.
    Example: -sc=0.5.
    Defaults to -sc=1.0.
-r
--rasterize
Output a rasterized image (PNG) instead of SVG.
-d=<int>
--dpi=<int>
DPI to use when rasterizing the image.
    Example: --dpi=300.
    Defaults to -d=96.
-e
--full-err
Print the full error message when an error occurs.
-tp=<str>
--tex-program=<str>
TeX program to use for compilation.
    Example: -tp=xelatex or -tp=lualatex.
    Defaults to -tp=pdflatex.
-ta=<str>
--tex-args=<str>
Arguments to pass to the TeX program.
    Example: -ta="$tex_args_ipython_variable".
    Defaults to None.
-nc
--no-compile
Do not compile the TeX code.
-s=<str>
--save-text=<str>
Save the TikZ or LaTeX code to file.
    Example: -s filename.tikz.
    Defaults to None.
-S=<str>
--save-image=<str>
Save the output image to file.
    Example: -S filename.png.
    Defaults to None.
-sv=<str>
--save-var=<str>
Save the TikZ or LaTeX code to an IPython variable.
    Example: -sv my_var.
    Defaults to None.

Contribute

Contributions are welcome from everyone! Whether you're reporting bugs, submitting feedback, or actively improving the codebase, your involvement is valuable. Here's how you can contribute:

  1. If you encounter any issues or have suggestions for improvements, please report them using the issues page.
  2. If you're interested in developing the software further, please refer to development guide.

Changelog

All notable changes to this project are presented below.

v0.3.1

🐞 Bug Fixes

  • Fixed DOCs links

v0.3.0

🚀 Features

  • Web documentation.
  • Flag (--print-tex) to print the full LaTeX document.
  • UTF-8 support.
  • Added support for Python 3.10.

🚨 Breaking Changes

  • Replaced --full-document and --implicit-pic with --input-type=<str>. -f and -i still working as aliases.
  • Changed the --as-jinja flag to --use-jinja.
  • Reworked the API to an object-oriented approach.

v0.2.1

🐞 Bug Fixes

  • Minor adjustments in the README and Getting Started Notebook.

v0.2.0

🚀 Features

  • Option to save output code to an IPython variable (-sv=<var_name>).
  • Flag (--no-compile) to prevent LaTeX compilation and image rendering.
  • Support for LaTeX \input{...} commands.

v0.1.1

🐞 Bug Fixes

  • Minor fixes in README.

🚀 Features

  • Added PyPI badge.

v0.1.0

  • First version released on PyPI.

Thanks

I had been using ITikZ for years. However, it doesn't update often and relies on the outdated pdf2svg to convert PDFs to images, which causes problems in Windows environments. Inspired by ITikZ and IPython TikZ Magic, I decided to create my own package, adding new features such as the ability to work with preambles and save the LaTeX result to IPython variables. I also switched from pdf2svg to Poppler, which works perfectly in Windows.

License

Copyright 2024 © Lucas Lima Rodrigues.

Distributed under the terms of the MIT License, Jupyter-TikZ is free and open-source software.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jupyter_tikz-0.3.1.tar.gz (16.0 kB view hashes)

Uploaded Source

Built Distribution

jupyter_tikz-0.3.1-py3-none-any.whl (13.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page