42

I have one .tex-document in which one graph is made by the python module matplotlib. What I want is, that the graph blends in to the document as good as possible. So I want the characters used in the graph to look exactly like the other same characters in the rest of the document.

My first try looks like this (the matplotlibrc-file):

text.usetex   : True
text.latex.preamble: \usepackage{lmodern} #Used in .tex-document
font.size    : 11.0 #Same as in .tex-document
backend: PDF

For compiling of the .tex in which the PDF output of matplotlib is included, pdflatex is used.

Now, the output looks not bad, but it looks somewhat different, the characters in the graph seem weaker in stroke width.

What is the best approach for this?

EDIT: Minimum example: LaTeX-Input:

\documentclass[11pt]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}

\begin{document}

\begin{figure}
\includegraphics{./graph}
\caption{Excitation-Energy}
\label{fig:graph}
\end{figure}

\end{document}

Python-Script:

import matplotlib.pyplot as plt
import numpy as np

plt.plot([1,2,3,4])
plt.xlabel("Excitation-Energy")
plt.ylabel("Intensität")
plt.savefig("graph.pdf")

PDF output:

enter image description here

7
  • 3
    Is scaling of your picture 100 percent? Are you using \includefigure[width=??] ? That may be the problem
    – Sleepyhead
    Jul 16, 2013 at 21:25
  • 2
    Can you add a link to an example out put, as well as the python code an the latex used to generate it? With out more information this will be very hard to debug.
    – tacaswell
    Jul 17, 2013 at 2:45
  • 2
    a good starting point is this document wiki.scipy.org/Cookbook/Matplotlib/LaTeX_Examples
    – gg349
    Jul 17, 2013 at 7:34
  • 1
    Have a look at the psfrag package. It allows you to replace tags in PostScript figures. That way, your plot-label will not only look exactly like the text of your document, the will be just as the rest of the text.
    – Schorsch
    Jul 17, 2013 at 13:01
  • 3
    As an update to me previous comment, apparently matplotlib and psfrag are no longer friends.
    – Schorsch
    Jul 17, 2013 at 18:35

4 Answers 4

30

The difference in the fonts can be caused by incorrect parameter setting out pictures with matplotlib or wrong its integration into the final document. I think problem in text.latex.preamble: \usepackage{lmodern}. This thing works very badly and even developers do not guarantee its workability, how you can find here. In my case it did not work at all.

Minimal differences in font associated with font family. For fix this u need: 'font.family' : 'lmodern' in rc. Other options and more detailed settings can be found here.

To suppress this problem, I used a slightly different method - direct. plt.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]. It is not strange, but it worked. Further information can be found at the link above.


To prevent these effects suggest taking a look at this code:

import matplotlib.pyplot as plt

#Direct input 
plt.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]
#Options
params = {'text.usetex' : True,
          'font.size' : 11,
          'font.family' : 'lmodern',
          'text.latex.unicode': True,
          }
plt.rcParams.update(params) 

fig = plt.figure()

#You must select the correct size of the plot in advance
fig.set_size_inches(3.54,3.54) 

plt.plot([1,2,3,4])
plt.xlabel("Excitation-Energy")
plt.ylabel("Intensität")
plt.savefig("graph.pdf", 
            #This is simple recomendation for publication plots
            dpi=1000, 
            # Plot will be occupy a maximum of available space
            bbox_inches='tight', 
            )

And finally move on to the latex:

\documentclass[11pt]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}

\begin{document}

\begin{figure}
    \begin{center}
        \includegraphics{./graph}
        \caption{Excitation-Energy}
        \label{fig:graph}
    \end{center}
\end{figure}

\end{document}

Results

Zoom of pdf document

As can be seen from a comparison of two fonts - differences do not exist (1 - MatPlotlib, 2 - pdfLaTeX) Comparison of fonts

5

tikzplotlib is here for this exact purpose. Instead of savefig(), use

import tikzplotlib

tikzplotlib.save("out.tex")

and include the resulting file in your LaTeX document via

\input{out.tex}

It's also easy to edit in case you need to change things in your plot after you created the file.

enter image description here

1
  • It's a nice idea but the package still has quite some issues with e.g. labels and label patches. I recommend having a look at the pgf backend.
    – Suuuehgi
    May 11, 2022 at 9:45
5

Alternatively, you can use Matplotlib's PGF backend. It exports your graph using LaTeX package PGF, then it will use the same fonts your document uses, as it is just a collection of LaTeX commands. You add then in the figure environment using input command, instead of includegraphics:

\begin{figure}
  \centering
  \input{your_figure.pgf}
  \caption{Your caption}
\end{figure}

If you need to adjust the sizes, package adjustbox can help.

3

I had difficulties getting Eleniums's answer to work for me. I specified 'figure.figsize' and 'font.size' in the matplotlib rc-params to be identical to the font size and textwidth of the LaTeX document, but there still was a noticeable difference in the text size of the label. I finally found out that the label font size in matplotlib is apparently indepentent of 'font.size'.

The following solution worked perfectly for me:

Python

W = 5.8    # Figure width in inches, approximately A4-width - 2*1.25in margin
plt.rcParams.update({
    'figure.figsize': (W, W/(4/3)),     # 4:3 aspect ratio
    'font.size' : 11,                   # Set font size to 11pt
    'axes.labelsize': 11,               # -> axis labels
    'legend.fontsize': 11,              # -> legends
    'font.family': 'lmodern',
    'text.usetex': True,
    'text.latex.preamble': (            # LaTeX preamble
        r'\usepackage{lmodern}'
        # ... more packages if needed
    )
})

# Make plot
fig, ax = plt.subplots(constrained_layout=True)
ax.plot([1, 2], [1, 2])
ax.set_xlabel('Test Label')
fig.savefig('test.pdf')

LaTeX

\documentclass[11pt]{article}    % Same font size
\usepackage[paper=a4paper, top=25mm, 
            bottom=25mm, textwidth=5.8in]{geometry}    % textwidth == W
\usepackage{lmodern}

% ...

\begin{figure}[ht]
    \centering
    \includegraphics{test.pdf}
    \caption{Test Title}
\end{figure}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.