Stop resizing, cropping and pixelated plots. Create beautiful Plots with Matplotlib and LaTex! Matplotlib integrates very well with LaTex, if configured correctly.

Determining the correct dimensions

The current dimensions of the text area can be determined in LaTex with \textwidth and \textheight. The layouts package allows converting those internal measures into inches.

\usepackage{layouts}

\newcommand{\printsizes}{
    Width: \printinunitsof{in}\prntlen{\textwidth}in \\
    Height: \printinunitsof{in}\prntlen{\textheight}in
}

Now use the \printsizes command where the plots should be inserted. Note those values down.

Configuring Matplotlib

This snipped enables the pgf-matplotlib backend. Pdflatex is used as tex-system for generating other formats such as pdf,png,… .

import matplotlib

matplotlib.use("pgf")
matplotlib.rcParams.update(
    {
        # Adjust to your LaTex-Engine
        "pgf.texsystem": "pdflatex",
        "font.family": "serif",
        "text.usetex": True,
        "pgf.rcfonts": False,
        "axes.unicode_minus": False,
    }
)

By default, the font and sizes of the document are used. Optionally the font size can be set with:

font = {'family' : 'sans',
        'weight' : 'normal',
        'size'   : 10}
matplotlib.rc('font', **font)

The figure size can be set globally too:

matplotlib.rcParams['figure.figsize'] = (width, height)  # Use the values from \printsizes

Plotting

Using the pgf-backend allows for some nice feature like inline LaTex.

import matplotlib.pyplot as plt

# ...
# create plot as usual
# ...

plt.xlabel("$x_1$")  # Latex commands can be used
plt.ylabel("$x_2$")
# Insert width and height from \printsizes
# A factor can be used to create some whitespace
factor = 0.9
plt.gcf().set_size_inches(3.43745 * factor, 3.07343 * factor)
# Fixes cropped labels
plt.tight_layout()
# Save as pgf
plt.savefig("plot.pgf")

Importing the Plot in LaTex

The pgf-file contains regular latex (pgf) commands. To import the plot in LaTex use \input{...}.

\usepackage{pgf}
% on pdftex
\usepackage[utf8]{inputenc}
\DeclareUnicodeCharacter{2212}{-}
% on luatex and xetex
% \usepackage{unicode-math}
% See https://github.com/matplotlib/matplotlib/issues/18826

% Now print the plot:
\input{path/to/plot.pgf}

Examples