Welcome to LaTeXiPy’s documentation!

Contents:

LaTeXiPy

PyPI version Test status Documentation Status Updates MIT License

Generate beautiful plots for LaTeX using your existing Matplotlib-based code.

You can also use this package to generate plots without using LaTeX. Just don’t run lp.latexify().

Usage

To plot in Python:

import latexipy as lp

lp.latexify()  # Change to a serif font that fits with most LaTeX.

with lp.figure('filename'):  # saves in img/ by default.
    draw_the_plot()
https://github.com/masasin/latexipy/raw/master/examples/img/sincos_defaults.png

To display in LaTeX:

\usepackage{pgf}
\input{filename.pgf}

See the examples directory for some example code, their resulting images, as well as an example LaTeX file and its output PDF.

Features

  • Automatically generate multiple plot types, such as PDF, PNG, and PGF for LaTeX.

  • Works with all Matplotlib-based packages, including Seaborn and Pandas.

  • Allows for easily changing the style temporarily.

Credits

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.

Installation

Stable release

To install LaTeXiPy, run this command in your terminal:

$ pip install latexipy

This is the preferred method to install LaTeXiPy, as it will always install the most recent stable release.

If you don’t have pip installed, this Python installation guide can guide you through the process.

From sources

The sources for LaTeXiPy can be downloaded from the Github repo.

You can either clone the public repository:

$ git clone git://github.com/masasin/latexipy

Or download the tarball:

$ curl  -OL https://github.com/masasin/latexipy/tarball/master

Once you have a copy of the source, you can install it with:

$ python setup.py install

Usage

To use LaTeXiPy in a project:

import latexipy as lp

Set up for LaTeX with:

lp.latexify()

And make your figures with:

with lp.figure('filename'):
    draw_the_plot()

Import from LaTeX with:

\usepackage{pgf}
\input{filename.pgf}

Example files

From the latexipy Github repository.

Minimum Working Example

sincos_plotter.py
import numpy as np
import matplotlib.pyplot as plt

import latexipy as lp

lp.latexify()

with lp.figure('sincos'):
    x = np.linspace(-np.pi, np.pi)
    y_sin = np.sin(x)
    y_cos = np.cos(x)
    plt.plot(x, y_sin, label='sine')
    plt.plot(x, y_cos, label='cosine')
    plt.title('Sine and cosine')
    plt.xlabel(r'$\theta$')
    plt.ylabel('Value')
    plt.legend()
sincos_report.tex
\documentclass{article}

\usepackage{pgf}

\begin{document}
  \begin{figure}[h]
    \centering
    \input{img/filename.pgf}
    \caption[LOF caption]{Regular caption.}
    \label{fig:pgf_example}
  \end{figure}
\end{document}

Plotting

Without LaTeX

If you are not making your plots for LaTeX, Matplotlib’s defaults are used. The typeface is sans-serif, and the font, a bit large. The default arguments save a PGF and PNG file in the img/ directory.

with lp.figure('sincos'):
    plot_sin_and_cos()
_images/sincos_no_latex.png

With LaTeX

If you are building for LaTeX, just lp.latexify()!

lp.latexify()

with lp.figure('sincos'):
    plot_sin_and_cos()
_images/sincos_defaults.png

Using custom parameters

By default, lp.latexify() uses lp.PARAMS, which has the following values:

_latexipy.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
FONT_SIZE = 8

PARAMS = {
    'pgf.texsystem': 'xelatex',  # pdflatex, xelatex, lualatex
    'text.usetex': True,
    'font.family': 'serif',
    'font.serif': [],
    'font.sans-serif': [],
    'font.monospace': [],
    'pgf.preamble': [
      r'\usepackage[utf8x]{inputenc}',
      r'\usepackage[T1]{fontenc}',
      ],
    'font.size': FONT_SIZE,
    'axes.labelsize': FONT_SIZE,
    'axes.titlesize': FONT_SIZE,
    'legend.fontsize': FONT_SIZE,
    'xtick.labelsize': FONT_SIZE,
    'ytick.labelsize': FONT_SIZE,
}

Passing a different dictionary to lp.latexify() causes these changes to be permanent in the rest of the code. For example, to increase the font size throughout:

examples.py
 93
 94
 95
 96
 97
 98
 99
100
101
    font_size = 10
    params = lp.PARAMS.copy()
    params.update({param: font_size
                   for param in params
                   if 'size' in param})
    lp.latexify(params)

    with figure('sincos_big_font_permanent'):
        plot_sin_and_cos()

You can call lp.latexify() multiple times throughout your code, but if you want to change the setting only for a few figures, the recommended approach is to use lp.temp_params(). This automatically reverts to the previous settings after saving (or attempting to save) the plot.

examples.py
87
88
89
90
    font_size = 10
    with lp.temp_params(font_size=font_size):
        with figure('sincos_big_font_temp'):
            plot_sin_and_cos()

Either way, the font size would have increased uniformly from 8 to 10 pt.

_images/sincos_big_font_temp.png

Note that lp.temp_params() can also take a custom dictionary which can do more fine-grained tuning of fonts.

examples.py
111
112
113
114
115
116
    with lp.temp_params(font_size=10, params_dict={
        'axes.labelsize': 12,
        'axes.titlesize': 12,
        }):
        with lp.figure('sincos_big_label_title'):
            plot_sin_and_cos()
_images/sincos_big_label_title.png

Reverting

To revert all changes made with lp.latexify() and other commands, just run lp.revert().

Avoiding repetition

If you keep passing the same arguments to lp.figure() (for example, an output directory, a set of filetypes, or a certain size), you can save it for reuse by using functools.partial(). After that, you can use it just like lp.figure(). Note that you would not be able to redifine an argument that you had previously applied.

figure = partial(lp.figure, directory=DIRECTORY)

with figure('sincos_partial'):
    plot_sin_and_cos()

where DIRECTORY is the default output directory. This pattern was used extensively in the Python file from the examples directory.

Using in LaTeX

To include a PGF file in your LaTeX document, make sure that the pgf package is loaded in the preamble.

\usepackage{pgf}

After that, you can include it in the correct location with:

\input{<filename>.pgf}

A minimum working example of an image within a figure is shown below.

\documentclass{article}

\usepackage{pgf}

\begin{document}
  \begin{figure}[h]
    \centering
    \input{img/filename.pgf}
    \caption[LOF caption]{Regular caption.}
    \label{fig:pgf_example}
  \end{figure}
\end{document}

Note that figures using additional raster images can only be included by \input{} if they are in the same directory as the main LaTeX file. To load figures from other directories, you can use the import package instead.

\usepackage{import}
\import{<path to file>}{<filename>.pgf}

A minimum working example of that scenario is shown below.

\documentclass{article}

\usepackage{import}
\usepackage{pgf}

\begin{document}
  \begin{figure}[h]
    \centering
    \import{/path/to/file/}{filename.pgf}  % Note trailing slash.
    \caption[LOF caption]{Regular caption.}
    \label{fig:pgf_example}
  \end{figure}
\end{document}

Technical Documentation

latexipy package

Module contents

LaTeXiPy
Provides
  1. An easy way of generating plots in multiple formats.

  2. Sensible defaults that fit perfectly with most LaTeX documents.

  3. Compatibility with Matplotlib-based packages.

  4. Easy restyling.

This documentation assumes that latexipy has been imported as lp:

>>> import latexipy as lp

You will probably use lp.figure() the most (once for each block):

>>> with lp.figure('filename'):
...     draw_the_plot()
latexipy.figure(filename, *, directory='img', exts=['pgf', 'png'], size=None, mkdir=True)[source]

The primary interface for creating figures.

Any Matplotlib-derived code in the scope of this context manager is valid, and should output as expected.

Parameters
  • filename (str) – The base name of the file, without extensions.

  • directory (Optional[str]) – The name of the directory in which to store the saved files. Default is ‘img’.

  • exts (Sequence) – A list of all the extensions to be saved, without the dot. Default is [‘pgf’, ‘png’].

  • size (Optional[Sequence[float, float]]) – The width and height of the figure, in inches. Default is figure_size().

  • mkdir (Optional[bool]) – Whether the directory should be created automatically if it does not exist. Default is True.

Raises
  • FileNotFoundError – If the target directory does not exist and cannot be created.

  • NotADirectoryError – If the target directory is actually a file.

  • PermissionError – If there is no permission to write to the target directory.

  • ValueError – If the format is not supported.

Notes

When integrating with LaTeX, the recommended format is PGF. PNG can be used externally, such as in blog posts or as embedded images, while PDF can be standalone, or inserted into LaTeX documents. A full list of supported formats can be found by calling plt.gcf().canvas.get_supported_filetypes_grouped()

latexipy.figure_size(width_tw=0.9, *, ratio=None, height=None, n_columns=1, max_height=8, doc_width_pt=345)[source]

Get the necessary figure size.

Parameters
  • width_tw (Optional[float]) – The width of the figure, as a proportion of the text width, between 0 and 1. Default is 0.9.

  • ratio (Optional[float]) – The ratio of the figure height to figure width. If height is specified, ratio is calculated from that and width. Default is the golden ratio.

  • height (Optional[float]) – The height of the figure in inches. If ratio is specified, height is ignored. Default is the golden ratio of the width.

  • n_columns (Optional[int]) – The number of equally sized columns in the document. The figure will never be larger than the width of one column. Default is 1.

  • max_height (Optional[float]) – The maximum height of the figure, in inches. Default is MAX_HEIGHT_INCH.

  • doc_width_pt (float) – The text width of the document, in points. It can be obtained by typing \the\textwidth in the LaTeX document. Default is 345.

Returns

  • width (float) – The figure width, in inches.

  • height (float) – The figure height in inches.

latexipy.latexify(params={'axes.labelsize': 8, 'axes.titlesize': 8, 'font.family': 'serif', 'font.monospace': [], 'font.sans-serif': [], 'font.serif': [], 'font.size': 8, 'legend.fontsize': 8, 'pgf.preamble': ['\\usepackage[utf8x]{inputenc}', '\\usepackage[T1]{fontenc}'], 'pgf.texsystem': 'xelatex', 'text.usetex': True, 'xtick.labelsize': 8, 'ytick.labelsize': 8}, new_backend='pgf')[source]

Set up Matplotlib’s RC params for LaTeX plotting.

Call this function before plotting the first figure.

Parameters
  • params (Optional[dict]) – A dictionary containing the RC params that need to be updated. Default is PARAMS. The defaults should be okay for most cases, but PARAMS can be updated via .update() as well.

  • new_backend (Optional[str|None]) – The backend to switch too. Default is PGF, which allows a nicer PDF output too.

Raises

ValueError – If the new backend is not supported.

Example

>>> params = PARAMS.copy()
>>> params.update({'font.family': 'sans-serif'})
>>> latexify(params)
latexipy.revert()[source]

Return to the settings before running latexify() and updating params.

latexipy.save_figure(filename, directory, exts, mkdir=True, from_context_manager=False)[source]

Save the figure in each of the extensions.

Parameters
  • filename (str) – The base name of the file, without extensions.

  • directory (str) – The name of the directory in which to store the saved files.

  • exts (Sequence) – A list of all the extensions to be saved, without the dot.

  • mkdir (Optional[bool]) – Whether the directory should be created automatically if it does not exist. Default is True.

  • from_context_manager (Optional[bool]) – Whether the function is being called from the figure context manager. This only affects the logging output. Default is False.

Raises
  • FileNotFoundError – If the target directory does not exist and cannot be created.

  • NotADirectoryError – If the target directory is actually a file.

  • PermissionError – If there is no permission to write to the target directory.

  • ValueError – If the format is not supported.

Notes

When integrating with LaTeX, the recommended format is PGF. PNG can be used externally, such as in blog posts or as embedded images, while PDF can be standalone, or inserted into LaTeX documents. A full list of supported formats can be found by calling plt.gcf().canvas.get_supported_filetypes_grouped()

latexipy.temp_params(font_size=None, font_family=None, font_serif=None, font_sans_serif=None, font_monospace=None, params_dict=None)[source]

Temporarily set Matplotlib’s RC params.

Parameters
  • font_size (Optional[int]) – The font size to use. It changes all the components that are normally updated with latexify(). If you want to change something individually, do so from within params_dict.

  • font_family (Optional[str]) – The font family to use.

  • font_serif (Optional[List[str]]) – A list of serif fonts to use.

  • font_sans_serif (Optional[List[str]]) – A list of sans-serif fonts to use.

  • font_monospace (Optional[List[str]]) – A list of monospace fonts to use.

  • params_dict (Optional[Dict[str, Any]]) – The dictionary of parameters to update, and the updated values. This is only applied after going through the rest of the arguments.

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

You can contribute in many ways:

Types of Contributions

Report Bugs

Report bugs at https://github.com/masasin/latexipy/issues.

If you are reporting a bug, please include:

  • Your operating system name and version.

  • Any details about your local setup that might be helpful in troubleshooting.

  • Detailed steps to reproduce the bug.

Fix Bugs

Look through the GitHub issues for bugs. Anything tagged with “bug” and “help wanted” is open to whoever wants to implement it.

Implement Features

Look through the GitHub issues for features. Anything tagged with “enhancement” and “help wanted” is open to whoever wants to implement it.

Write Documentation

LaTeXiPy could always use more documentation, whether as part of the official LaTeXiPy docs, in docstrings, or even on the web in blog posts, articles, and such.

Submit Feedback

The best way to send feedback is to file an issue at https://github.com/masasin/latexipy/issues.

If you are proposing a feature:

  • Explain in detail how it would work.

  • Keep the scope as narrow as possible, to make it easier to implement.

  • Remember that this is a volunteer-driven project, and that contributions are welcome :)

Get Started!

Ready to contribute? Here’s how to set up latexipy for local development.

  1. Fork the latexipy repo on GitHub.

  2. Clone your fork locally:

    $ git clone git@github.com:your_name_here/latexipy.git
    
  3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:

    $ mkvirtualenv latexipy
    $ cd latexipy/
    $ python setup.py develop
    
  4. Create a branch for local development:

    $ git checkout -b name-of-your-bugfix-or-feature
    

    Now you can make your changes locally.

  5. When you’re done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:

    $ flake8 latexipy tests
    $ python setup.py test or py.test
    $ tox
    

    To get flake8 and tox, just pip install them into your virtualenv.

  6. Commit your changes and push your branch to GitHub:

    $ git add .
    $ git commit -m "Your detailed description of your changes."
    $ git push origin name-of-your-bugfix-or-feature
    
  7. Submit a pull request through the GitHub website.

Pull Request Guidelines

Before you submit a pull request, check that it meets these guidelines:

  1. The pull request should include tests.

  2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst.

  3. The pull request should work for Python 2.6, 2.7, 3.3, 3.4 and 3.5, and for PyPy. Check https://travis-ci.org/masasin/latexipy/pull_requests and make sure that the tests pass for all supported Python versions.

Tips

To run a subset of tests:

$ py.test tests.test_latexipy

Credits

Development Lead

Contributors

None yet. Why not be the first?

History

1.0.1 (2017-08-24)

  • Fix README rendering for Github and PyPI.

1.0.0 (2017-08-24)

  • First release on PyPI.

Indices and tables